Transfer e-mail from GMail to another IMAP server

So, my e-mail server setup work really well so I decided so move my main email from Google Apps to a self hosted server instead.
I did some research on what tool to use since I really need to bring my mail with me. (note, this will not bring your contacts).

I looked at imapcopy but some people were having issues with it and recommended imapsync instead. This is a software the creator charges €50 for but this blog recommended using this site to download it for free. And as far as I can see, it seems legit. You decide.

The first step is to setup the server to start receive mail for that new domain. Login to postfixadmin and add a new domain and a new mailbox for your user. Make a DKIM-key-pair. Routing new incoming email is easily done in the DNS by changing the MX records. Remember to look over your SPF-record as well, to see if it’s still ok after the switch.

Step 1 - Dependencies

imapsync is a Perl script which depends on some tools. Follow these instructions to install what you need to run imapsync.

tar xzf Mail-IMAPClient-2.2.9.tar.gz
cd Mail-IMAPClient-2.2.9
perl Makefile.PL
make install

aptitude install  libmail-imapclient-perl
aptitude install  libdigest-md5-file-perl
aptitude install  libterm-readkey-perl
aptitude install  libio-socket-ssl-perl
aptitude install  libfile-spec-perl
aptitude install  libdigest-hmac-perl

Step 2 - Install imapsync

Install imapsync

tar xvzf imapsync-1.525.tar.gz
cd imapsync-1.525.tar.gz
make install

Step 3 - Test the connection to both mailboxes

Testing the sync

#the command is imapsync --host1 --host2

#this command, when using --dry and --justfolders is just testing and actually not creating and moving mail
#also, when using Gmail as the 'from' server we exclude All Mail since it's just copies and a mess. Your inbox and other folders will have the mail.
imapsync --host1 --user1 --password1 MASKED --host2 --user2 --password2 MASKED --syncinternaldates --ssl1 -ssl2 --noauthmd5 --split1 100 --split2 100 --exclude All Mail --dry --justfolders

Step 4 - Sync mailboxes

Doing the sync.
Run the exact same command as in Step 3 if everything looked good. Just omit the ‘—dry’ and ‘—justfolders’ flags.

imapsync --host1 --user1 --password1 MASKED --host2 --user2 --password2 MASKED --syncinternaldates --ssl1 -ssl2 --noauthmd5 --split1 100 --split2 100 --exclude All Mail

And now we wait. This can take a few hours if you have a huge mailbox. Mine was about 8k messages and took two hours.

We also have to wait for the DNS changes to go through so email can still come to your old inbox. Usually takes about a few hours, but can take up to 48h.
No mail are lost during this time.