In general, emission lines occur in gases that are optically thin, or in atmospheres that have a temperature inversion (i.e. are hotter closer to the observer).

In an optically thin gas, if excited atoms or ions are radiatively deexcited, then the photons produced can escape to an observer. If continuum absorption/emission is unlikely then this leads to an observed emission line. Examples include most nebulae.

The second case arises because if you have a hot layer on top of a cool layer, then the light we receive from the "photosphere" will come from a hotter layer at the wavelength of a strong radiative transition (closer to the observer) compared with the continuum. As the hotter layer is brighter,  we see an emission line. The exact opposite case to the formation of an absorption line, which arises when light at the central wavelength of a transition arises from a higher, cooler layer.

A temperature inversion requires a way of non-radiatively depositing heat in the hotter layer, otherwise radiative diffusion would eliminate it. An example is a stellar chromosphere, which is above and hotter than the photosphere, and heated by magnetic fields. This can produce high temperature emission lines. However, the chromosphere is (a) patchy and (b) thin enough to allow light of most wavelengths through it, so we still view the solar photosphere with its absorption lines, but with the addition of emission lines from the hotter chromosphere.