Bash script to tidy GMail/Google Workspace e-mail using offlineimap and notmuch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Props to @hsanson in | |
# https://github.com/neomutt/neomutt/issues/1975#issuecomment-669181335 for | |
# providing me the inspiration to finally put this together based on *weeks* of | |
# research | |
# Steps required to properly delete e-mail via IMAP (not JMAP) from GMail | |
# supported accounts, which also includes accounts hosted through Google | |
# Workspace | |
# | |
# Assumptions, using offlineimap v8.0.0 with imaplib2 v3.0.6 and notmuch v0.37 | |
# E-mails to be deleted are tagged with 'trash' | |
# 1. Find e-mail files that are not currently in trash and are tagged trash | |
# 2. Delete any records of each that are in folders other than archive | |
# 3. Remove all X-Keywords from records that are in archive | |
# 4. Remove MAILDIR hash from filename | |
# 5. Move the result to the corresponding trash folder in the correct account | |
# TODO: | |
# * Any code that's reusable, particularly the move mail bit can be put into a | |
# function and reused | |
# Tidy to Trash | |
for i in $(notmuch search --output=messages 'not path:/trash/ and tag:trash') | |
do | |
for j in $(notmuch search --output=files tag:trash and $i) | |
do | |
ACCOUNT=$(echo $j | awk -F/ '{print $5}') | |
DIR=$(echo $j | awk -F/ '{print $6}') | |
if [ $DIR == 'inbox' ] || [ $DIR == 'spam' ] || [ $DIR == 'sent' ] | |
then | |
/usr/bin/systemd-cat echo "Remove $j in $DIR" | |
rm $j | |
elif [ $DIR == 'archive' ] | |
then | |
/usr/bin/systemd-cat echo "Remove X-Keywords from $j" | |
sed -in 's/X-Keywords.*/X-Keywords:/g' $j | |
FILE=${j##*/} | |
FILE_NOUID=${FILE/,U=[0-9]*:/:} | |
FILE_NOUID=${FILE_NOUID/,U=0-9]*/} | |
/usr/bin/systemd-cat mv -uv $j ~/mail/$ACCOUNT/trash/cur/$FILE_NOUID | |
fi | |
done | |
done | |
# Tidy to Archive from Inbox/Spam | |
for i in $(notmuch search --output=messages 'not path:/archive/ and tag:archive') | |
do | |
for j in $(notmuch search --output=files tag:archive and $i) | |
do | |
ACCOUNT=$(echo $j | awk -F/ '{print $5}') | |
DIR=$(echo $j | awk -F/ '{print $6}') | |
if [ $DIR == 'inbox' ] | |
then | |
/usr/bin/systemd-cat echo "Remove $j in $DIR" | |
rm $j | |
elif [ $DIR == 'spam' ] | |
then | |
FILE=${j##*/} | |
FILE_NOUID=${FILE/,U=[0-9]*:/:} | |
FILE_NOUID=${FILE_NOUID/,U=0-9]*/} | |
/usr/bin/systemd-cat mv -uv $j ~/mail/$ACCOUNT/archive/cur/$FILE_NOUID | |
elif [ $DIR == 'archive' ] | |
then | |
/usr/bin/systemd-cat echo "Remove X-Keywords from $j" | |
sed -in 's/\\Inbox//g' $j | |
fi | |
done | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment