Piero V.

Bulk delete emails with Python

Recently, I had to check a legacy email address we used at home until a few years ago.

We almost stopped using it, but some services are still tied to it. The result is that whenever I need to check it, I find tons of spam, and the web interface is kinda bad, so it takes ages to delete all of it.

Some months ago, I learned to interact with IMAP from Python when I wrote a script to download and back up email accounts.

So, I modified it to output a CSV with all the senders and subjects of the emails in the mailbox. The scripts left a column empty to mark the emails that should be deleted with an x.

Then, I wrote another script to read the modified changes and to move the marked emails to the trash for a final review before emptying it.

Recently, I found myself in the same situation again, but I did not keep these scripts, so I had to write a new one.

It did not take much, but since it might be helpful to someone (at least the future me), I decided to share it here.

It takes the parameters to connect to the IMAP server on the command line. Then, it takes the action (write-csv to create the CSV with the list of emails, or read-csv to read it to send the changes to the server), and finally the name of the CSV file.

The script is released in the public domain, and, as always, it comes without any warranty.