Encrypt OfflineIMAP and msmtp password with GnuPG

It is possible to greatly simplify one's workflow with OfflineIMAP and msmtp by storing email passwords for all mail accounts in encrypted files. These files can be decrypted using a single GnuPG key.

Update: I now use the awesome pass that makes gpg-encrypted passwords much more comfortable. It also offers a generator an the best is that all the encrypted passwords can be managed with git without a hassle.

OfflineIMAP and msmtp in combination with mutt form a great way to manage your mail via console. I assume that you set you already got OfflineIMAP and msmtp working. The Archlinux wiki contains two very good pages to get you started (OfflineIMAP and msmtp). Here I will briefly explain how you can store your mail password encrypted on the disk and use it with both of them. You only have to unlock the private key with a password you can choose. This is great as the session is opened for some time. You only have to enter one password for all your mail accounts!

It is required that you have a GnuPG key. You can create one with a self-explanatory dialog with the following command. Only use keys you generated on a computer you trust!

gpg2 --full-gen-key

Next step is to encrypt your password with the following command. Replace YourPassword with your pass and YourName with the recipient of the GnuPG key you want to use (for example the full name you used in the previous step). This of course works even if your name contains non-ASCII characters. Remember to delete the history file of your shell (e.g. ~/.histfile or ~/.zsh_history) afterwards as it now contains the plain password. If you find this unsecure write your password in a file and use cat pw-file instead of echo "YourPassword". This will still not protect you against keyloggers, so use a safe computer.

echo "YourPassword" | gpg2 --encrypt --recipient "Your Name" -o ~/.mail-tudo-passwd.gpg

Now create a python file with the following code. In my config it is called ~/.offlineimap.py, but you can change it to what you want.

import subprocess

def mailpasswd(account):
    path = "/home/fabian/.mail-%s-passwd.gpg" % account
    return subprocess.check_output(["gpg", "--quiet", "--batch", "-d", path]).strip()

In your .offlineimaprc file add these two lines to the general block as well as to the account block. Make sure to delete/uncomment any remotepass line.

# ...
pythonfile = ~/.offlineimap.py
# ...

[Repository tudo-remote]
# ...
remotepasseval = mailpasswd("tudo")
# ...

In your .msmtprc file remove the password line and inser the following line.

passwordeval "gpg --quiet --for-your-eyes-only --no-tty --decrypt ~/.mail-tudo-passwd.gpg"

There you have it.