It recently has been shown experimentally that the focusing provided by a longitudinal nonuniform high magnetic field can significantly improve electron beam dose profiles. This could permit precise targeting of tumors near critical areas and minimize the radiation dose to surrounding healthy tissue. The experimental results together with Monte Carlo simulations suggest that the magnetic confinement of electron radiotherapy beams may provide an alternative to proton or heavy ion radiation therapy in some cases. In the present work, the external magnetic field capability of the Monte Carlo code PENELOPE was utilized by providing a subroutine that modeled the actual field produced by the solenoid magnet used in the experimental studies. The magnetic field in our simulation covered the region from the vacuum exit window to the phantom including surrounding air. In a longitudinal nonuniform magnetic field, it is observed that the electron dose can be focused in both the transverse and longitudinal directions. The measured dose profiles of the electron beam are generally reproduced in the Monte Carlo simulations to within a few percent in the region of interest provided that the geometry and the energy of the incident electron beam are accurately known. Comparisons for the photon beam dose profiles with and without the magnetic field are also made. The experimental results are qualitatively reproduced in the simulation. Our simulation shows that the excessive dose at the beam entrance is due to the magnetic field trapping and focusing scattered secondary electrons that were produced in the air by the incident photon beam. The simulations also show that the electron dose profile can be manipulated by the appropriate control of the beam energy together with the strength and displacement of the longitudinal magnetic field.