This is to do with the electrons in the metal atoms. When a piece of the metal is heated, if there is enough energy supplied to the atoms, their electrons are excited and are promoted (jump up) to higher energy levels. Once an electron is promoted it is known to be in an excited state. However, excited states are unstable, therefore the electron relaxes back down to a lower, more stable energy level. What is important to appreciate here is that there is a difference in energy between the two levels the electron has excited to and relaxed back to. As the electron relaxes to a lower energy level it gives off energy in the form of a photon which corresponds to the energy difference of the two energy levels involved in this situation.
This photon given off will be in the visible region of the EM spectrum if the electron had relaxed to the 2nd energy level. This is why certain metals give off different colours when heated as their electrons, having de-excited to energy level 2, give off energy in the form of a visible photon. Example: potassium = lilac.