Spring clean your Gmail account with Python
and make the most of Google's 15 GB free storage...
Keeping a healthy and tidy inbox has always been difficult for me. And my past sins had been accumulating over time!
With spring cleaning around and constant reminders from Google to free up storage to continue receiving emails, I thought it'd be perfect to get rid of age-old unnecessary emails from food ordering confirmations, Amazon order purchases, auto-pay reminders, and credit card junkies from my Gmail inbox and free up some space.
Google offers 15 GB of free space across Google Drive, Gmail, and Google Photos. I had exhausted all of this for myself, the major contribution coming from Gmail.
I did a quick check on the state of my inbox and there were more than 200K emails lying. Bulk deleting emails from Gmail is unintuitive, unreliable, very slow and boring for a developer. So, I decided to take another route - write my own short Python script to automate this! Below I will present the magic soap solution and a few prerequisites to get you going to carry out this spring cleaning for yourself.
Prerequisites:
- IMAP is an Internet standard protocol used by email clients to retrieve and access email messages from a mail server. For your python script to access Gmail, you would have to enable IMAP in your Gmail account.
Log in to Gmail > Settings > See all settings > Forwarding and POP/IMAP > Enable IMAP
2. Enable "Less secure app access" by clicking on your google photo > Manage your Google Account > Security > Less Security App Access > Turn On access.
Remember to switch it back OFF once you are done with running the script.
Now, the fun stuff...
The magical python soap solution:
imaplib module implements IMAP protocol in Python - we can leverage it out for our use case.
The script below is divided into 4 main sections:
A couple of things to keep in mind before running the script as-is:
- Replace the 'username' and 'password' fields in the script below with your account credentials.
- By default, the script deletes emails from the 'All Mail' folder. You can change the folder to delete the emails from. To do so, you can list all the available folders/labels to IMAP using 'imap.list()' command and then select the one you would like to delete emails from.
- By default, the script is designed to delete all emails from your account which belong to the promotions category and are not marked as important. You can specify different criteria as you would while performing an advanced search on your Gmail inbox. For instance, to delete all emails from a particular sender, say, iDontLikeYourEmails@gmail.com, simply change the 'gmail_search' criterion as shown: gmail_search = '"from: iDontLikeYourEmails@gmail.com"'
- Running the script will permanently delete the selected emails. Be careful in specifying the search criteria and the folder correctly. You can always run only selected portions of the script by commenting the rest. For instance, you can make sure that you aren't accidentally deleting your entire mailbox by checking the 'msg_count' variable and commenting Section 2 and 3 in the code. Similarly, you can just choose to move all the selected emails to Trash first by commenting the Section 3 and once you are satisfied with your Trash, simply uncomment the Section 3 and re-run the script to actually permanently delete all those emails.
Finally, here is the magic soap solution for your inbox cleanup:
import imaplib
# account credentials and other configs
# replace with you Gmail username and password
username = "replace with your Gmail username"
password = "replace with your Gmail password"
folderToDeleteEmailsFrom = '"[Gmail]/All Mail"'
trashFolder = '[Gmail]/Trash'
# create IMAP4 with SSL
imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
# authenticate
imap.login(username, password)
# list all the mailboxes present
print(imap.list())
# SECTION 1: select the mailbox to delete emails from
imap.select(folderToDeleteEmailsFrom)
gmail_search = '"category:promotions NOT is: important"'
typ, [msg_ids] = imap.search(None, 'X-GM-RAW', gmail_search)
msg_count = len(msg_ids)
print("Found message count: ", msg_count)
if msg_count == 0:
print("No new messages matching the criteria to be deleted.")
else:
if isinstance(msg_ids, bytes):
# if it's a bytes type, decode to str
msg_ids = msg_ids.decode()
# SECTION 2: imap store command allows us to batch perform an operation
# on a bunch of comma-separated msg ids
msg_ids = ','.join(msg_ids.split(' '))
print("Moving to Trash using X-GM_LABELS.")
imap.store(msg_ids, '+X-GM-LABELS', '\\Trash')
# SECTION 3: Once all the required emails have been sent to Trash,
# permanently delete emails marked as deleted from the selected folder
print("Emptying Trash and expunge...")
imap.select(trashFolder)
imap.store("1:*", '+FLAGS', '\\Deleted') # Flag all Trash as Deleted
imap.expunge()
# SECTION 4: close the mailbox once the task is done
print("Done. Closing connection & logging out.")
imap.close()
# logout
imap.logout()
This is how I quickly got back ~5-6 GB free storage back for myself. I'm glad that I didn't take the Google upsell of purchasing additional storage.
You can do it too. Happy cleaning up!
still making round 5 years later... just helped me👏🏽👏🏽👏🏽👏🏽👏🏽
Hi Bro, I am not able to do with outlook mail just changed the account details can U tell what changes need to be done for outlook mail
Its a fantastic code i am trying the code to delete mails at once from many months i tried with ur code it working well Thank you for your code bro 🙂
Thanks for sharing this Himanshu Gupta !
It helped me release ~2GB of email roughly ~35k emails. Great work - thanks!