Here's my humble explanation, as well as me trying to recall it.
First, all nucleis spin. For some reason it just does. The spin is caused by unpaired protons / neutrons I believe..
Nucleis carry charge (proton is +ve, and neutrons are neutral), and spinning charge creates magnetic field. This is just like how moving charges create magnetic fields. This is why they act like a little magnet.
Now, when you put strong magnetic fields (apply) onto these nucleis, half will align, and another half will oppose the direction of the field.
But wait, they don't really align. They precess / wobble around the "aligning" axis, just like a spinning top. This is because of preservation of angular momentum.
The frequency of precession depends on the strength of the magnetic field, and the nuclei's gyromagnetic ratio. This gyromagnetic ratio depends on the composition of the nuclei. In other words, it differs from nuclei to nuclei.
Wait, here's another catch. Not exactly half aligns and opposes the magnetic field (more like precess to align and precess to oppose, anyhow..). There is always an excess little bit (9 atom per 2 million or something) that wobble / precess to have it's magnetic axis align with the external field.
Now, here comes the nitty gritty part.
As you know, when you apply a magnetic field, the nucleis will spin up and against. They wobble at a larmor frequency / precession frequency whatever you call it.
Ever heard about opera singers breaking glass? That is called resonance. This is because the natural frequency of glass just happens to be the same with the opera singer's voice frequency.
It happens in wobbling nucleis as well. As you put radiofrequency pulses (they are made from accelerating charges, which means alternating magnetic field), and if the RF signal's frequency equals the larmor / precession frequency, resonance occurs, and the nuclei wobbles to another direction. They absorbed the energy of the RF pulse.
Now, by continually putting RF pulses onto the nuclei, it will keep being forced to wobble somewhere else. Until the RF pulse is turned off.
When the RF pulse is turned off, the nuclei will relax back to the aligning state, giving off an RF pulse at the same frequency. This can be detected.
Now, because the RF pulse depends on the precession frequency, which depends on the nuclei type, the computer can distinguish between atom types.
Oh, and I think this resonance only happens to those extra 9 / 2 million atoms, since the others that align up and down cancel each other somehow...