Flying behind a planet will cause a spacecraft to gain energy. Flying in front of it will cause a spacecraft to lose energy.
References
Johnson, B. "The Slingshot Effect, Alias 'Gravity Assist': How Spacecraft Accelerate in Planetary Flybys." http://www.dur.ac.uk/bob.johnson/SL/.