It's a fairly complicated biochemical process called "bioluminescence" that happens in somewhat different ways in different species. It involves specialized pigmentation molecules that give off energy in the form of light when the presence of similarly specialized enzymes causes them to oxidize.
In addition to attracting a suitable mate, the chemicals involved make them unappetizing to predators.
You can find more details here: http://funadvice.com/r/156fl10f9fr
Well fireflies are nocturnal, luminous beetles, they use it to attract a partner and its actually them using special light-emitting organs in the abdomen.