# Encrypt all incoming emails with gpg
2024-09-15T14:40:43Z

EDIT: I updated the script to keep headers intact:
=> /code/encrypt-all-incoming-mails/

If for some reasons you don't want to keep your emails unencrypted on your server
=> https://dataswamp.org/~solene/2024-09-12-email-selfhost-to-protonmail.html

You may encrypt all of them as long as your public key is available:
=> https://dataswamp.org/~solene/2024-08-14-automatic-emails-gpg-encryption-at-rest.html

As far as I'm concerned, I don't keep my emails on my server, I mainly use one computer, so I download (rsync) my Maildir and run mutt on it.

So I wrote a little script to encrypt all my incoming emails without requiring dovecot. However, the whole email is encrypted, headers are unreadable. That's fine, mutt know how to open them, they're just not sorted.
Actually, I decrypt them after downloading the messages and before opening mutt.

First, set up a .forward file on your server home:

```
echo "|/usr/local/bin/encrypt-mail.sh -r you@domain.tld" > ~/.forward
chmod 600 ~/.forward
```

The encrypt-mail.sh file is:

```
#!/bin/sh
# encrypt incoming mail
#
# 	"Initial setup:\n"
# 	"echo "|/usr/local/bin/encrypt-mail.sh -r you@domain.tld" > ~/.forward\n"
# 	"chmod 600 ~/.forward\n"

usage() {
	printf "usage: $0 [-r email@domain.tld] [-h]\n"
	printf "	-h: show this help\n"
	printf "	-r: set recipient email, default to user@hostname\n"
	printf "---\n"
	exit 1
}

# default user email
recipient="$(whoami)@$(hostname)"

while getopts 'r:h' c
do
    case $c in
	h) usage ;;
        r) recipient="${OPTARG}" ;;
    esac
done


# check if Maildir/new is here
d="$HOME/Maildir/new"
test ! -d "${d}" && mkdir -p "${d}"

# create a path to a new email
# format:
# gettimeofday().uniqu-id.gethostname()
timeofday="$(date +%s)"
uniq_id="$$"
myhostname="$(hostname | sed -e 's;/;\\057;' -e 's;:;\\072;g')"

new_mail_filename="$HOME/Maildir/new/${timeofday}.${uniq_id}.${myhostname}"

# encrypt
gpg --output "${new_mail_filename}" --encrypt --armor --recipient "${recipient}"
```

One may want a better setup to keep different IMAP clients synchronised.
Someone told me Solène had a better idea 👼.


---
Comments?
=> mailto:bla@bla.si3t.ch?subject=Encrypt-all-incoming-emails-with-gpg

Instructions:
=> /log/_commentaires_.txt