NEW YORK — Former U.S. Rep. Anthony Weiner, whose penchant for sexting strangers ended his political career and led to an investigation that upended the presidential race, pleaded guilty Friday to criminal charges in connection with his online communications with a 15-year-old girl.

Weiner pleaded guilty to a charge of transmitting sexual material to a minor and could get years in prison. He agreed not to appeal any sentence between 21 and 27 months in prison.

In court, Weiner cried as he apologized to the teenager with whom he exchanged sexually explicit texts.

"I have a sickness, but I do not have an excuse," the former Democratic congressman said.

Weiner was already in federal custody ahead of the hearing. The judge told him he would have to register as a sex offender.

The FBI began investigating Weiner in September after the 15-year-old North Carolina girl told a tabloid news site, the Daily Mail, that she and the disgraced former politician had exchanged lewd messages for several months.

She also accused him of asking her to undress on camera.

The investigation led FBI agents to seize his laptop computer, which led to the discovery of a new cache of emails that Democratic presidential candidate Hillary Clinton had sent to Huma Abedin, Weiner's wife.

In late October, just days before the election, FBI Director James Comey stunned the country by announcing that his agency was reopening its closed investigation into Clinton's handling of State Department business on a private email server so it could analyze the newly discovered correspondence.

That inquiry was brief. Comey announced shortly before the election that the new emails contained nothing to change his view that Clinton could not be charged with a crime. But Clinton partly blamed her loss to Republican Donald Trump on Comey's announcement.

Weiner, who represented New York in Congress from 1999 to 2011, resigned after revelations that he was sending sexually explicit messages to multiple women.

He ran for New York City mayor in 2013 and was leading several polls until it was revealed he had continued his questionable behavior. His failed mayoral bid was the subject of the documentary "Weiner."