When it comes to copying/moving emails between 2 imap/gmail servers, we prefer larch – a ruby gem.
Since gmail provides imap, it shouldn’t be any surprise to see it working with larch. What makes larch special is that its special-handling for Gmail’s labels.
Install Ruby & Gems
If you don’t have ruby, you can run following.
apt-get install ruby1.9.1 ruby1.9.1-dev rubygems1.9.1 irb1.9.1 ri1.9.1 rdoc1.9.1 build-essential libopenssl-ruby1.9.1 libssl-dev zlib1g-dev libsqlite3-dev
There is rvm installation method also which is more popular among rubyist. Since you did not have ruby previously, I assume above command will be your preferred choice.
Larch can be installed using any rubygem.
gem install larch
Below is an example command to move emails from OLD-HOST to NEW-HOST where OLD-USER and OLD-PASS are username and password on old server, while NEW-USER and NEW-PASS are username and password on new server.
larch --from imap://OLD-HOST --from-user OLD-USER --from-pass OLD-PASS --to imap://NEW-HOST --to-user NEW-USER --to-pass NEW-PASS --all
As you can see larch needs many parameters but they all are obvious and self-explanatory.
Don’t worry if you forget any larch parameter. Larch will prompt you for missing parameter except, “from” and “to”.
--all flag moves mails inside all folder. If a folder doesn’t exist on destination server, larch will create it automatically.
Copying All Gmail Mails
For Gmail, because of its label-system, you can use a syntax like:
larch --from imaps://imap.gmail.com --to imaps://imap.gmail.com --from-folder '[Gmail]/All Mail' --to-folder '[Gmail]All Mail'
It will copy mails from “All Mail” to “All Mail”. Larch will prompt you for username & password since we did not specify it in above command.
Delete copied email
In all larch commands, you can add
--delete flag so once a mail is copied to new server, it gets deleted from old server.
You no need to use delete flag in case you are worried about duplicated. Running same larch commands again and again doesn’t create duplicate emails on destination server. Larch automatically checks for duplicates.
This also means you can setup a cron job to run larch command, in case you want to backup your mails.
Check Larch Readme on Github for more examples.