Worms do not have lungs, but they have developed a way to breathe by drawing oxygen directly into their circulatory systems. When a worm is moist, it absorbs air through its mucus-coasted skin by dissolving it.
After the worm absorbs air, the oxygen immediately enters its circulatory system. Its blood, now oxygenated, is pumped by the worm's hearts into its head. The worm's moving body pushes the blood toward the back of its body, and the hearts pump it forward again in a continuous cycle. Carbon dioxide leaves the blood by dissolving back to the skin.
This process is called diffusion. That's when molecules move from an area of higher concentration to one of lower concentration. An earthworm needs oxygen for its cells to function, but its cells are always using that oxygen up, so the levels of oxygen an earthworm has inside its body are always lower than they are outside. This keeps the worm's oxygen levels within a healthy range.
The earthworm needs to stay moist in order for its body to absorb oxygen and release carbon dioxide. If the mucus on a worm's body dries out, which can happen if the worm is exposed to sunlight for too long, it will be unable to breathe.