As it turns out, all atoms have a very specific set of discrete energy levels their electrons can exist in. When an electron “jumps” between energy levels, it emits or absorbs light at a frequency whose energy corresponds to the energy difference of the jump. When light of the frequency that produces the D lines hits sodium atoms, they can absorb the light and jump to the corresponding higher energy level. This creates the dark absorption lines. When the sodium atom electrons then fall back down to their previous energy level, they emit the difference in energy as light at the D line frequency, creating the bright emission lines.
The details of this situation are quite a bit more complicated, and in the case of molecules, their energy states can be characterized by their vibration and rotation in addition to their electrons transitions, but the very basics of the emission and absorption of light can be easily understood: photons with precisely the correct amount of energy to change the energy state of the system can be absorbed or emitted.
Flames, like the ones Fraunhofer used, are very hot. Their atoms are excited – i.e. in higher energy states – and so they are prone to spontaneous emission. Similarly, the interior of the sun is extremely hot and a lot of photons are emitted in it. The sun's upper layers are comparatively cooler (though still very hot!), so their atoms are in lower energy states. The atoms higher in the sun absorb the light that comes up from deeper inside, thus producing the dark absorption lines we see imprinted on the solar spectrum.