Yes, that is exactly the solution. You need a transistor or relay. If you used a relay, you would still need to use a transistor since the MCU pin cannot supply enough current for a relay coil. See the scheamtic below. Your electromagnet is basically a relay coil too so if you want to use a transistor only just sub in your electromagnet into the relay coil.
If you want to use a relay, connect your electromagnet to the primary contacts of the relay. Don't forget to incldue the flyback diode since both the relay coil and electromagnet are inductive and so will produce a voltage spike when current is interrupted and this spike can burn out the transistor.
When current in an inductor decreases or is interrupted, the magnetic field collapses and the inductor dumps the energy in the magnetic field into producing a voltage to keep pushing the current to maintain the same current level. If it has to push the current very hard (i.e. through a newly opened switch) then the voltage will be very high.
Without more details about your electromagnet and current draw, we can't help you pick a relay or transistor. You can use either an NPN transistor or NMOS. The NPN is what is shown in the schematic and will require a properly sized base resistor. The NMOS does not require such a resistor.