Jesus' genealogy includes several women, a rarity among Jewish genealogies. These women are Gentiles--Tamar and Rahab (both Canaanites), Ruth (Moabite), and Bathsheba (Hittite)-- all of whom had had illicit or questionable sexual relationships with Jewish men, which resulted in the birth of children. Tamar disguised herself as a prostitute and seduced Judah, her father-in-law, producing twins. Rahab, a prostitute who plied her trade on the wall at Jericho, had a child (Boaz) with Salmon, whether through marriage or not we don't know. Ruth, a widower, crawled under the covers of Boaz, and Obed was born. These women are king David's ancestors.
Then David had an affair with Bathsheba, a married woman, and sent her husband Uriah to the frontlines of battle to be killed. David and Bathsheba wed and had Solomon who became Israel's new king.
Why does Matthew lists these women in Jesus' genealogy? First, to show that despite mistakes and moral indiscretions, God works providentially to bring about his will. Second, to show that God loves, forgives, and uses people on the margins to fulfill his plans. Third, to show his plan of redemption includes Gentiles. Fourth, to ease the scandal surrounding Mary's pregnancy, who stands in the line of these women.
From a human perspective Mary was a tainted woman because she became pregnant prior to marriage. Joseph, to whom she was espoused, knew Jesus was not his child. Although he learned through a vision the truth about Mary, her neighbors did not. They all looked on her as an immoral woman and Jesus as her illegitimate child (John 8:41).
Finally, for Matthew's audience living decades after Jesus, this genealogy offers them hope and encouragement because they, too, have been marginalized. Rejected by non-messianic Jewish family members and friends for following Jesus and rubbing shoulders with Gentile Christ followers, they have been kicked out of synagogues and declared dead. But God accepts them and will use them to do great things just as he used the women in Jesus' genealogy, despite public opposition.
Jesus is the savior of those on the margins. They may be rejected by man, but they are accepted by God!