There are two explanations possible stemming from the fact that the definition of $m$ in the formula is ambiguous. Well, perhaps Einstein had only one of the two meanings in mind in his original paper but I'm afraid I wouldn't know that as I haven't read it. Be that as it may one should recall that special relativity mixes space and time and therefore also momentum and energy and the full formula relating all these fundamental quantities has to be
$$E^2 = m_0^2c^4 + p^2c^2$$
where $m_0$ is the rest mass of the particle (zero for photons) whose importance lies in the fact that it is invariant w.r.t. Lorentz transformations (rotations and boosts).
So the first explanation is that the famous formula only holds in the object's rest frame ($p=0$). But such a rest frame isn't available for photons so that formula indeed isn't valid for them.
The other explanation is through the concept of relativistic mass. In that case the $m$ takes on the meaning of apparent mass because the faster the object goes the harder it will be to accelerate it (because of finite speed of light). So formally one can still talk about the photon having a relativistic (or effective) mass $m = E/c^2$. But this concept of mass runs in all kinds of problems so its usage is discouraged.
You dont need quantum mechanics to argue here, you can simply look to the equation with the rest mass, instead the one with the relativistic mass. This is $$E^2= m_0^2 c^4 + p^2 c^2$$
So, any particle with zero rest mass still has Energy coming from the linear momentum.
If we see by Louis de Broglie's way, he says that light has dual nature, it can be in the form of waves or in the form of matter by formula $\lambda =h/p$, $h$ is Planck's constant which shows the wave nature and $p$ is momentum which explain the matter wave.