Every plumbing fixture has a self-sealing water trap, which stores about two cups of water in a U-shaped bend that sits below the piping and the fixture. When there is no water in the pipe due to cracks or non-use, odors and flies can escape. A venting problem also can prevent the trap from resealing after the water flows down the drain.
Pour two gallons of hot water into seldom-used drains and treat all drains with bleach. If the flies come back, there may be something wrong with your trap or a drain line.