I used to keep a local backup of my Gmail mails with OfflineImap. But I never felt comfortable with this solution because of OfflineImap being fully bidirectional. Which means my mails in the cloud are not protected from me messing with their local versions.

In the mean time I found out about mbsync (from the isync project). It particularly features fine-grained options to let you defined which source is authoritative, thus restricting the synchronization to one direction.

Let’s install mbsync and its dependencies !

$ sudo aptitude install isync ca-certificates

Just in case, don’t forget to enable IMAP access to you Gmail account.

Create a new destination directory and an empty configuration file:

$ mkdir -p ~/gmail-backup
$ touch ~/.mbsyncrc

Then add the following parameters in ~/.mbsyncrc:

IMAPAccount      gmail
Host             imap.gmail.com
User             kevin@gmail.com
Pass             xxxxxxxxxxxxxx
UseIMAPS         yes
CertificateFile  ~/gmail-backup/gmail.crt
CertificateFile  ~/gmail-backup/google.crt
CertificateFile  /usr/share/ca-certificates/mozilla/Equifax_Secure_CA.crt

IMAPStore  gmail-cloud
Account    gmail

MaildirStore  gmail-backup
Path          ~/gmail-backup/
Inbox         ~/gmail-backup/Inbox

Channel   gmail
Master    :gmail-cloud:
Slave     :gmail-backup:
Create    Slave
Expunge   Slave
Sync      Pull
# Exclude everything under the internal [Gmail] folder, except archived mails
Patterns  * ![Gmail]* "[Gmail]/All Mail"

Before going further we need to fetch Gmail’s certificates:

$ openssl s_client -connect imap.gmail.com:993 -showcerts 2>&1 < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sed -ne '1,/-END CERTIFICATE-/p' > ~/gmail-backup/gmail.crt
$ openssl s_client -connect imap.gmail.com:993 -showcerts 2>&1 < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tac | sed -ne '1,/-BEGIN CERTIFICATE-/p' | tac > ~/gmail-backup/google.crt

Then all you have to do is to launch mbsync itself:

$ mbsync gmail
Reading configuration file ~/.mbsyncrc
Resolving imap.gmail.com... ok
Connecting to ok
Connection is now encrypted
Logging in...
Channel gmail
Selecting slave MyLabel... Maildir notice: cannot read UIDVALIDITY, creating new.
0 messages, 0 recent
Selecting master MyLabel... 77 messages, 0 recent
Pulling new messages........................................................

Now to keep your local backup fresh don’t forget to launch mbsync regularly in the background.

Related content