The spacecraft effectively "bounces" off of the planet, similar to the way a rubber ball would bounce off of a speeding car as it passes by. The car transfers its velocity to the rubber ball. Of course, the spacecraft doesn't actually bounce off of the planet, but it whips around it in a hyperbolic trajectory. Check Wikipedia for a more detailed description of how this works.

Which type are you talking about? Powered or unpowered? In a powered flyby, the craft dives towards the object, adding velocity, before executing a burn when it is travelling close to the escape velocity of the object, rasing it's velocity high enough to escape. Since the energy of an object goes as the square root of velocity, the craft gains more energy than it would have if it had just executed the burn without the flyby, since it hjas the energy from the dive.