How do CMB photons 'gain energy when they pass through normal regions of space with matter' and 'lose energy when they pass through voids'?
It is the late time integrated Sachs Wolfe effect.

As they travel towards us, apart from the general expansion, photons from the CMB gain energy when they fall into potential wells (where matter is). Of course, they lose it again as they emerge on the other side of the well, but the cosmic expansion means that the well isn't quite as deep by the time that happens. As a result, photons gain a little energy compared to the average CMB sightline.

The opposite happens for voids. Energy is required to enter a void (the potential is higher than average), but all this energy is not retrieved because the potential flattens due to expansion as the photon traverses it. Hence the directions of voids would be a bit cooler.