The Effects of Vaginal Stimulation on Pain Tolerance
One study in rats (because there are some things you can't do to human subjects) found that the analgesic affect of vaginal stimulation is related to the hormone estradiol. As in humans, vaginal stimulation raised the (apparent) pain threshold of female rats (as measured by whether they cry out when their tails were shocked). When the rats, whose ovaries had been surgically removed, were treated with estradiol, their pain tolerance increased. When the rats were given both estradiol and progesterone the effect disappeared. Estradiol is one of two forms of estrogen present in females. It is primarily produced in the ovaries, although it can also be produced in some cells (in particular, fat cells) from testosterone. Since the rats in the study had no ovaries, it's likely that while estradiol is one factor involved in increasing pain tolerance during sexual stimulation, it is not the only one.
In fact, the major male sex hormone, testosterone, which is involved in the sexual response of both sexes, also plays a role in pain tolerance. An experiment on sparrows found that the amount of time it took for the birds to remove their feet from uncomfortably hot water was increased when the birds were given testosterone and decreased when they were given agents that blocked testosterone. The researchers actually theorize that this change may be due to the above-noted conversion of testosterone to estradiol. Testosterone therapy has also been found to have a positive effect on chronic pain disorders like fibromyalgia, though it's unclear if this effect is due to testosterone itself or a related steroid synthesized from its conversion. It's also possible that the hormones that become elevated post-orgasm, most notably oxytocin and prolactin, could have a pain-reducing impact. Oxytocin in particular is not well understood (and frequently grossly mischaracterized), but could have a role in post-orgasm feelings of relaxation, which in turn could affect perceptions of pain.
In any case, the pain-reducing effects of sexual stimulation are sadly short-lived. Sex is great if you want to temporarily knock out a migraine or forget that your spine is an asshole who can't seem to stay in place (and if you're using it that way, please be careful what positions you choose), but it can't actually fix pain. For that you typically need actual medical care.