Synchronize emails between mail servers

26 Jan 2017 in Email, IMAP

For this, I use imapsync an Email IMAP tool for syncing, copying and migrating email mailboxes. To set it up on an Ubuntu machine (shamelessly stolen from Joeri Verdeyen's blog here and here) use:

# install dependencies
sudo apt-get install makepasswd rcs perl-doc libio-tee-perl git \
    libmail-imapclient-perl libdigest-md5-file-perl \
    libterm-readkey-perl libfile-copy-recursive-perl \
    build-essential make automake libunicode-string-perl

# clone git repository
git clone git://

# build/install
cd imapsync
mkdir dist
sudo make install

The make install above may tell you about missing perl dependencies. If so, call cpan with sudo and install the required dependencies like:

sudo cpan
# and from cpan> prompt
install Unicode::String # or whatever make install told you

Then to synchronize emails for a given email account, just do:

imapsync --host1 host1 --user1 user1 --password1 pass1 \
         --host2 host2 --user2 user2 --password2 pass2

A simple bash script to automate this procedure is:

while getopts 'f:t:' flag; do
  case "${flag}" in
    f) from="${OPTARG}" ;;
    t) to="${OPTARG}" ;;
if [ -z $from ]; then
    echo "From host not specified (hint -f)! Exiting"
    exit 1
if [ -z $to ]; then
    echo "To host not specified (hint -t)! Exiting"
    exit 1
while read line; do
    user=$(echo $line | cut -f 1 -d ' ')
    pass=$(echo $line | cut -f 2 -d ' ')
    imapsync \
        --host1 $from \
        --user1 $user \
        --password1 $pass \
        --host2 $to \
        --user2 $user \
        --password2 $pass

Save it into a file called, make it executable and call it like this:

./ -f host1 -t host2 <<< "user password"

Or you can create a file with user/password pairs (space delimited) and call it like:

./ -f host1 -t host2 < email-password.list

Useful when moving a domain from one server to another.