Copy emails between IMAP servers

I was assigned an email account which I could only access through a dated online interface called Outlook Web Access or using IMAP4. I like to keep all my email accounts together by importing them to my Gmail account. However, Gmail doesn’t allow IMAP importing and this email provider doesn’t allow forwarding so I ran into an impasse.

Kidnapped email

To get around this problem I tried several programs, but they either required a complicated setup of an SMTP server, which also altered the email headers, or didn’t work with IMAP SSL. The solution at the end was the following python script, which I run from a raspberry pi every 10 minutes as a cron job: