Skip to content

How I Used Python to Automate Cleaning 160k Unread Emails

  • October 20, 2021

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.  

How I Used Python to Automate Cleaning 160k Unread Emails_1_211019

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 

How I Used Python to Automate Cleaning 160k Unread Emails_2_211019

 

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

How I Used Python to Automate Cleaning 160k Unread Emails_3_211019

 

 Step 3: Select the mailbox to delete emails from 

How I Used Python to Automate Cleaning 160k Unread Emails_4_211019

 

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

How I Used Python to Automate Cleaning 160k Unread Emails_5_211019

 

 Step 5: Empty trash folder 

How I Used Python to Automate Cleaning 160k Unread Emails_6_211019

 

 Step 6: Logout 

How I Used Python to Automate Cleaning 160k Unread Emails_7_211019

 

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. 

RELATED NEWS

Getting Started with an Enterprise Data Model: Moving Beyond Excel

Many (if not all) financial firms began their data journey using Excel. It’s a tool that many are comfortable using and...

by Colleen Avallone