We consider the gravitational generation of the massive Z-boson field of the standard model, due to the natural breaking of its conformal invariance during inflation. The electroweak symmetry restoration at the end of inflation turns the almost scale-invariant superhorizon Z-spectrum into a hypermagnetic field, which transforms into a regular magnetic field at the electroweak phase transition. The mechanism is generic and is shown to generate a superhorizon spectrum of the form B~1/L on a length-scale L regardless of the choice of inflationary model. Scaled to the epoch of galaxy formation such a field suffices to trigger the galactic dynamo and explain the observed galactic magnetic fields in the case of a spatially flat, dark energy dominated Universe with GUT-scale inflation. The possibility of further amplification of the generated field by preheating is also investigated. To this end we study a model of Supersymmetric Hybrid Inflation with a Flipped SU(5) grand unified symmetry group.