Resources

How I Used Python to Automate Cleaning 160k Unread Emails

Written by Sal Fadel | Oct 20, 2021 2:55:00 AM

Return to Resources

First things first… You’re probably wondering why I had 160,000 unread promotional emails in email account to begin with, and how I let it get that out of control. For the last five years, I have used my Gmail account as my go-to “sign-up” email. Every subscription, promotion, advertisement, and website that I needed to add my email to, I did. To say the least, it got out of hand quickly, and I simply couldn’t keep up. Once I hit 30,000 unread emails, I gave up and figured someday I would figure out a way to automate deleting them.  

Finally, I did just that! If you are anything like me and have tons of unread (and likely useless) emails, I’ll show you how I did it.  

 

TEMPORARILY CHANGE YOUR GMAIL SECURITY SETTINGS

The first and most risky step is changing your Gmail security settings to allow less secure apps to access your Gmail account. To do this, you will want to go to your Google Account Settings, then click Security and then toggle to allow less secure apps. I highly recommend that after you are done cleaning up your emails, you turn off this setting.  

Once that is complete, we can dive into writing the Python script. Here is the process and code I used.

 

PYTHON SCRIPT PROCESS

Step 1: Import imaplib 

 

 Step 2: Use imap to connect to Gmail and  authenticate the user 

 

 Step 3: Select the mailbox to delete emails from 

 

Step 4: Search and find promotional emails that are not marked important and batch move them to the trash folder 

 

 Step 5: Empty trash folder 

 

 Step 6: Logout 

 

This process worked great and took just over 10 minutes to delete the 160K promotional email. My next evolution is to export all the unsubscribe links at the bottom of the emails and automate the unsubscribe process.  

Disclaimer: Continuus Technologies and its employees are not responsible for any loss of data or emails as a result of running this script. Please run this script at your own discretion and risk.