the outer electron in magnesium is excited by absorbing the heat energy from the N=1 stage to higher energy levels when it starts to drop back down to the N=2 level it losses energy in the form of visible light this is part of the Balmer series
hope that helps