# Automatic Gmail’s Trash & Spam folders cleanup

Since some time I’ve been thinking about a possible way to delete my Gmail’s Trash & Spam folders content automatically without having to bother doing it manually every single time I wanted to check my mail and clean it up. (I love keeping everything in place and having my Trash&Spam folders empty as they should be makes me pretty happy)

A few years ago when Mutt was my main mail client I had the need to filter my mail through IMAP and while googling around for that I found out a great piece of software: imapfilter. Today while analyzing the above quoted issue I suddenly told myself: “Hey, but why don’t you use your dear and old friend imapfilter to fulfil your needs?”

After a few minutes I came up with a small lua script that was doing exactly what I wanted: my Trash&Spam folders are no longer crowded and I finally don’t have to delete mails twice! But here they come a few details about my script:

options.timeout = 120

options.subscribe = true

account = IMAP {
server = 'imap.gmail.com',
ssl = 'ssl3'
}

trash = account['[Gmail]/Trash']:is_undeleted()

account['[Gmail]/Trash']:delete_messages(trash)

account['[Gmail]/Spam']:delete_messages(spam)

The script does two things:

1. It checks whether a mail is not marked as “deleted” (moving an e-mail into the Trash does not mark it as “to be deleted” automatically) already and removes it.
2. It checks whether a mail on the Spam folder has been answered (I never had to answer a single e-mail contained into my Spam folder)  and if not removes it.

Using the above script is really easy (you should run imapfilter on interactive mode first to generate Gmail’s certificates, do that before having cron to run the script for you or otherwise it’ll just hang), just make sure to have imapfilter installed on your system and then run it through cron every half an hour or less depending on your needs:

crontab -e

*/30 * * * * imapfilter -c /home/user/imapfilter.lua >> /home/user/imapfilter.log

Please also remember to setup appropriate permissions on the config file since it contains your Gmail’s password and most of all make sure that your Spam folder is visible through IMAP (this option can be found on the label menu available under your Gmail’s settings) otherwise imapfilter will just report an error.

Enjoy!