Backup Gmail with getmail

August 07, 2015

Backing up a Gmail account is pretty simple with getmail. The instructions below are based on the excellent article Backup Gmail with getmail on ArchWiki. Check it out for more details.

For the sake of anonymity, let's imagine we have two Gmail accounts, foo@bar.baz and i@haz.mail, that we want to backup. To do it with getmail, we'll write a couple of configuration files and a shell script to kick it off.

Make sure that IMAP is enabled for your accounts under Settings -> Forwarding and POP/IMAP:

Create the directories to store email for both accounts:

$ mkdir -p "~/backups/email/foo@bar.baz"
$ mkdir -p "~/backups/email/i@haz.mail"

Create a bunch of requisite directories for getmail:

$ cd "~/backups/email/foo@bar.baz"
$ mkdir cur new tmp
$ cd "~/backups/email/i@haz.mail"
$ mkdir cur new tmp

Write a getmail configuration file for each account:

~/backups/email/foo@bar.baz/getmailrc:

[retriever]
type = SimpleIMAPSSLRetriever
server = imap.gmail.com
mailboxes = ("[Gmail]/All Mail",)
username = foo@bar.baz
password = aligator3

[destination]
type = Maildir
path = ~/backups/email/foo@bar.baz/

[options]
verbose = 2
message_log = ~/backups/email/foo@bar.baz/log
read_all = false
delivered_to = false
received = false

Note that the password is stored in plaintext, so use caution.

~/backups/email/i@haz.mail/getmailrc:

[retriever]
type = SimpleIMAPSSLRetriever
server = imap.gmail.com
mailboxes = ("[Gmail]/All Mail",)
username = i@haz.mail
password = aligator3

[destination]
type = Maildir
path = ~/backups/email/i@haz.mail

[options]
verbose = 2
message_log = ~/backups/email/i@haz.mail/log
read_all = false
delivered_to = false
received = false

Finally, write a script to kick it off:

backup.sh:

#!/usr/bin/env bash

function getmail() {
  GETMAIL=`which getmail`
  CONFIG_DIR="~/backups/email/$1"
  $GETMAIL -g "$CONFIG_DIR" > "$CONFIG_DIR/out" 2> "$CONFIG_DIR/err"
}

getmail "foo@bar.baz"
getmail "i@haz.mail"

Run the script manually, or stick it in a cron job, and enjoy sweet backup bliss.