SEOUL, South Korea — A former director of South Korea’s main spy agency was sentenced to four years in prison on Wednesday on charges of ordering a clandestine online campaign to help the 2012 election of President Park Geun-hye, who has since been impeached.

Won Sei-hoon, director of the National Intelligence Service from 2009 to 2013, was convicted of violating laws that bar public servants from campaigning for political candidates and prohibit the powerful spy agency from interfering in domestic politics.

After the ruling on Wednesday at the appeals court in Seoul, the capital, Justice Kim Dae-woong had Mr. Won arrested in the courtroom and sent him to jail.

In the run-up to the December 2012 election, Mr. Won directed a secret team of psychological warfare agents to work with hired private bloggers on an online smear campaign against Ms. Park’s political rivals, according to the prosecutors’ indictment.