Moths are not really "attracted" to a flame, they're actually doing what they are evolved to do which is use light as a compass to help them get where they're going. To make a long scientific story short, the moth is simply fooled into thinking the flame is the light it needs but instead it becomes disoriented by it and mistakenly gets too close.
The moth's need of light and it's lack of ability to discern the danger of the flame leads to it's being drawn into it. It's then either smart, or lucky enough, to save itself in time or else it winds up injured by something it thought it needed.
I too have mistaken the glow of a flame for the light of the sun and had my wings singed for my mistake.