Encrypt OfflineIMAP Password

I use the following method, which works fairly well:

1) Store your passwords in separate gpg encrypted files. For example ~/.passwd/<accountname>.gpg

2) Create a python extension file with a name of your choosing (e.g., ~/.offlineimap.py), with the following contents:

def mailpasswd(acct):
  acct = os.path.basename(acct)
  path = "/home/<username>/.passwd/%s.gpg" % acct
  args = ["gpg", "--use-agent", "--quiet", "--batch", "-d", path]
  try:
    return subprocess.check_output(args).strip()
  except subprocess.CalledProcessError:
    return ""

3) Modify your .offlineimaprc file to tell it about the python file, and to tell it how to read your passwords

[general]
pythonfile = ~/.offlineimap.py
# ...

[Repository <reponame>]
# add this line for each remote repository
remotepasseval = mailpasswd("<accountname>")

If you have several accounts that get checked simultaneously (separate threads), and you use gpg-agent, then it will ask for you passphrase for each account. I prime the agent by creating a file (echo "prime" | gpg -e -r [email protected] > ~/.passwd/prime.gpg), and priming the gpg agent by decrypting this file on launch of offlineimap. To do this, add the following to the end of ~/.offlineimap.py:

def prime_gpg_agent():
  ret = False
  i = 1
  while not ret:
    ret = (mailpasswd("prime") == "prime")
    if i > 2:
      from offlineimap.ui import getglobalui
      sys.stderr.write("Error reading in passwords. Terminating.\n")
      getglobalui().terminate()
    i += 1
  return ret

prime_gpg_agent()

Another method of leaving offlineimap running with knowledge of your password, but without putting the password on disk, is to leave offlineimap running in tmux/screen with the autorefresh setting enabled in your ~/.offlineimaprc

You need to add autorefresh = 10 to the [Account X] section of the offlineimaprc file, to get it to check every 10 minutes. Also delete any config line with password or passwordeval.

Then run offlineimap - it will ask for your password and cache it in memory. It will not exit after the first run, but will sleep for 10 minutes. Then it will wake up and run again, but it will still remember your password.

So you can leave a tmux session running with offlineimap, enter your password once, and offlineimap will be fine there after.


Loving the answer from @kbeta. However subprocess.check_output() was only introduced in python 2.7 - so here is a version of offlineimap.py that will work with older versions of python:

import os
import subprocess

def mailpasswd(acct):
    acct = os.path.basename(acct)
    path = "/home/hamish/.passwd/%s.gpg" % acct
    args = ["gpg", "--use-agent", "--quiet", "--batch", "-d", path]
    proc = subprocess.Popen(args, stdout=subprocess.PIPE)
    output = proc.communicate()[0].strip()
    retcode = proc.wait()
    if retcode == 0:
        return output
    else:
        return ''