For syncing my email I have been using offline IMAP. This has been an excellent workflow for me, the only thing I didn’t like is keeping my passwords in plain text. To solve this problem I have decided to handle the passwords with Bitwarden. I have recently made the switch to Bitwarden from KeePass and the ability to do this sort of thing gives loads of points to Bitwarden.

To accomplish this I decided to use the remotepassfile parameter in the ‘.offlineimaprc’. I could have used a python script but I didn’t fancy hacking with python (I’m not that good at it) and I wanted to use the Bitwarden cli.

The flow I went for is:

  1. Go to Bitwarden and get the passwords and save them to a tmp file.
  2. Run offlineimap that will use said file.
  3. Remove the tmp file when everything is done.

I would like to add that I have already set up the Bitwarden cli and logged in so in the script all I have to do is see if Bitwarden is unlocked. I have also already got OfflineIMAP set up but with using passwords in the ‘.offlineimaprc’.

Below I have an example snippet from a ‘.offlineimaprc’ and a script for syncing email. In the script I wanted to see if Bitwarden was unlocked first, so I don’t have to put in my password if I didn’t need to. The other thing I am using is the ‘trap’ to remove the password file and ensure it’s removed after the email has finished syncing. This is the first thing I do in the script so even if the script fails somewhere it will still remove the password file.

1
2
3
4
5
6
7
8
9
#
# ~/.offlineimaprc
#

[Repository main]
type = IMAP
remotehost = host.com
remoteuser = email@example.com
remotepassfile = /tmp/pw.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/env sh
#
# /usr/local/bin/mail-sync.sh
#
set -e

#
# First thing to do is remove the file when the script ends
#
trap "rm /tmp/pw.txt" EXIT;

#
# Test to see if Bitwarden is unlocked if not then run the "unlock" command.
# You will need to put in your master password if Bitwarden needs unlocking.
#
bw get template item > /dev/null || export BW_SESSION="'bw unlock --raw'"

#
# Get the password and save it to a temporary file
#
bw get password <id> > "/tmp/pw.txt";

#
# Run offlineimap
#
offlineimap