If you use gmail, you might have noticed that you cannot create a filter to permanently delete a message. The closest you can get is to mark it as read and move it to the trash.

This is a little bit annoying when trying to filter messages you want to make 100% sure you do not read, such as nastygrams from exes or annoying in-laws.

The following script solves this problem by purging emails matching a sender from a certain folder (in this case, [Gmail]/Trash).

To use, put your gmail credentials in your .netrc:

machine imap.gmail.com
    login user@domain.com 
    password my_pasSWor3d

then, call the script periodically using cron:

*/10 * * * * ~/scripts/emptygmailtrash.py

The script is as follows, and can be downloaded here.

# This script will scan a folder on an IMAP server and delete any messages
# from a partcular email address.

# receiving, sending mail
import imaplib, smtplib
# credentials for account info
import netrc 

# mail host
host = "imap.gmail.com"

# folder where email is stored
trash_folder = "[Gmail]/Trash"
server = imaplib.IMAP4_SSL(host)

# fetch login info from .netrc
credentials = netrc.netrc()
login, account, password = credentials.authenticators(host)

# go to the trash folder
typ,data = server.search(None, 'FROM', '"annoying_inlaw@domain.tld"')

for num in data[0].split():
    typ, data = server.fetch(num, '(RFC822)')
    # mark as deleted
    server.store(num, '+FLAGS', '\\Deleted')

# purge deleted messages