The general formula for the probability of radiation of a twisted photon by a classical current is derived. The general theory of generation of twisted photons by undulators is developed. It is proved that the probability to record a twisted photon produced by a classical current is equal to the average number of twisted photons in a given state. The general formula for the projection of the total angular momentum of twisted photons given the energy, the longitudinal projection of momentum, and the helicity is obtained. The symmetry property of the average number of twisted photons produced by a charged particle moving along a planar trajectory is found. The explicit formulas for the average number of twisted photons generated by undulators in both the dipole and wiggler regimes are obtained. It is established that, for the forward radiation of an ideal right-handed helical undulator, the harmonic number n of the twisted photon coincides with its projection of the total angular momentum m . As for the ideal left-handed helical undulator, we obtain that m =-n . It is found that the forward radiation of twisted photons by a planar undulator obeys the selection rule that n +m is an even number. It turns out that the average number of twisted photons produced by the undulator and detected off the undulator axis is a periodic function of m in a certain spectral band of the quantum numbers m .