Relieving pain by massage
Short Answer
What you're referring to is called Delayed Onset Muscle Soreness (DOMS).
We don't really know what causes DOMS, but it's most likely caused by a cascade effect started my muscle injury. Also, we aren't sure if massages (or what type of massages) really help relieve the pain.

What is Delayed Onset Muscle Soreness (DOMS)?
Delayed onset muscle soreness (DOMS) is the sensation of muscular discomfort and pain during active contractions that occur 24–48 h after strenuous exercise. The initial symptoms are most evident at the muscle-tendon junction and thereafter spread throughout the entire muscle.(ref)
Physiopathology of DOMS
The mechanism is not completely understood and several theories have been proposed, namely: (ref)

lactic acid
muscle spasm
connective tissue damage
muscle damage
inflammation
enzyme efflux

The underlying cause is probably a conjunction of 2 or more of these theories. However, ultimately, the underlying transversal cause is muscle microtrauma. There are a few interesting findings that support this:

High-intensity eccentric contractions induce performance decrements and DOMS (ref),(ref)

Concentric exercises seems to cause no soreness (ref)

Eccentric contractions are high force and are associated with muscle damage (ref)

Creatinine, Potassium(K) (and sometimes Myoglobin) excretion (urine levels) and Creatine Kinase(CK), K and Neutrophil levels in blood are increased after intense exercise. This is also seen in acute rhabdomyolysis, a condition in which damaged skeletal muscle tissue breaks down. (Ref: Harrison's Principles of Internal Medicine, 17th Ed, Chapter 273: Acute Renal Failure)



The effects of massage on DOMS
A massage MAY indeed reduce pain in DOMS (ref), however, most studies' results are inconsistent and hindered by methodological flaws(ref) such as lack of control of the placebo effect or the subjectivity of pain.
A study by Smith et al suggests that sports massage will reduce DOMS when administered
2 hours after the termination of eccentric exercise. They also found lower CK levels, higher cortisol levels and a prolonged elevation of neutrophils in the blood of massaged groups (ref). This might mean lower muscle trauma and inflammation due to a reduced migration of neutrophils (to the muscle) and higher levels of serum cortisol.
The increment in the blood flow to the muscles during a massage might also be implicated in the process, by restoring oxygen and nutrients required to muscle remodeling. However, there is no clinical evidence of this fact and a study strongly rebutes this (ref)
Hyperstimulation of the nerve endings in the affected muscles might give a sense of pain relief, in a context of microtrauma. (ref)