Here's why:
* The outer core is liquid: It's made of molten iron and nickel, which are excellent conductors of electricity.
* Convection currents: Heat from the Earth's inner core drives convection currents in the outer core, causing the molten metal to move.
* Electric currents: This movement of electrically conductive material creates electric currents.
* Magnetic field generation: These electric currents, in turn, generate a magnetic field around the Earth, similar to how a wire carrying an electric current produces a magnetic field.
This process is known as the geodynamo, and it's a complex and constantly changing phenomenon. The Earth's magnetic field is constantly fluctuating and can even reverse its polarity over geological time scales.