Decluttering Mailbox Using Python

Decluttering Mailbox Using Python

Featured on Hashnode

I've had so many unread emails in my inbox because they were promotional content, or I was just too lazy to read when they came in. Now imagine opening your mailbox and seeing over a thousand emails — screams in 1917!! How can I declutter as fast as possible?

Now I know Gmail has a delete feature, but I believe we're meant to "automate the boring stuff with python," and you may learn something new or not.

In this article, I will show you how to set up a script to send unread/unwanted messages from your inbox to trash using IMAPlib and how to delete unread/unwanted messages using IMAPClient permanently.

Let's jump right into it!

Prerequisites

  • Python
  • Gmail account
  • ImapClient [optional]

Setting up your Gmail account

IMAP stands for Internet Mail Access protocol. According to Wikipedia, it is "an Internet standard protocol used by email clients to retrieve email messages from a mail server over a TCP/IP connection.”

To get started, we need to set up a Gmail account for the process to be successful. I made the following changes to my Gmail account, which enabled IMAP and turned on less secured apps.

  1. First, open Gmail, click on the settings ⚙️ icon and click See all settings to enable IMAP.
  2. On the next page, click on the Forwarding and POP/IMAP tab.
  3. In the IMAP Access section, select Enable IMAP. Then click Save changes. If you need more help, kindly visit this Gmail help page.
  4. To turn on less secured apps, navigate to your Google dashboard by clicking on your account avatar in the upper right-hand corner of your screen and then click My Account or navigate to myaccount.google.com.
  5. Then choose Sign-in & security, scroll down until you see the option Allow less secure apps, and turn the access on.

If you still can’t log in after doing the above, kindly visit here for official Google help support.

How to trash your emails using IMAPlib

The IMAP library is an inbuilt python library used for accessing and manipulating emails over IMAP. The code below logs you into the desired email address. After logging in, we select the desired mailbox to see a list of all available mailboxes to select from using print(mail.list()).

Starter code for IMAPlib

The criterion for emails to be sent to the trash in this section are:

  • Unread emails.
  • Emails based on a specific subject.
  • Emails based on a specific sender.
import imaplib
import getpass
username =  input("Enter the email address: ")
password = getpass.getpass("Enter password: ")
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(username, password)
mail.select("INBOX")

Trashing all unread emails

The code below sends all unread emails to the trash. You never can tell if you need any email, so you have thirty (30) days before Gmail removes it from the trash. First, we search through the emails setting the criteria to "UNSEEN" (which is the flag for unread messages). The variable result is an exit code of the command, while messages are a list that contains an object of type byte. Finally, we loop through the emails in the list and put them in the trash folder.

results, messages = mail.search(None, 'UNSEEN')
messages = messages[0].split()
for x in messages:
  result, message = mail.store(x, '+X-GM-LABELS', '\\Trash')
mail.close()
mail.logout()

Trashing all emails with a particular subject

Here, we search the selected mailbox using our desired criteria. You should replace "Title" with your desired subject in the code below:

results, messages = mail.search(None, '(SUBJECT "Title")')
messages = messages[0].split()
for x in messages:
  result, message = mail.store(x, '+X-GM-LABELS', '\\Trash')
mail.close()
mail.logout()

Trashing all emails from a specific sender

Here, we search the mailbox using our desired criteria. It would be best if you replaced"abc@xyz.com" with your preferred email address in the code below:

results, messages = mail.search(None, '(FROM "abc@xyz.com")')
messages = messages[0].split()
for x in messages:
  result, message = mail.store(x, '+X-GM-LABELS', '\\Trash')
mail.close()
mail.logout()

Here I'll briefly talk about the methods used.

  • search() is a method used to look through the selected mailbox, it takes two arguments; a charset and a criterion. The charset can be set to None.
  • store() is a method used to change the flag or label of a message; it takes three arguments; the message, the command, and the flag.
  • close() is a method used to close the selected mailbox.
  • logout() is a method used to close the connection to the server.
  • '+X-GM-LABELS' a label is treated as a folder to make changes to messages using IMAP commands.

How to permanently delete your emails using IMAPClient

While researching this article, I came across the IMAPClient library. From its official documentation, I discovered that: "although IMAPClient actually uses the imaplib module from the Python standard library under the hood, it provides a different API."

Using IMAPClient to delete emails will not send the emails to the trash folder; they will be permanently deleted. Therefore, you should BE SURE you want to delete your emails before using any code snippets here permanently.

Starter Code for IMAPClient

To use IMAPClient, you have to install the package using the command below:

pip install imapclient

Next, we import the library and set the server of our email address.

from imapclient import IMAPClient
import getpass
server = IMAPClient('imap.gmail.com', use_uid=True)
username =  input("Enter the email address: ")
password = getpass.getpass("Enter password: ")
server.login(username, password)
select_info = server.select_folder("INBOX")

The criterion for emails to be sent to the trash in this section are:

  • Unread emails.
  • Emails based on a specific subject.
  • Emails based on a specific sender.

Permanently deleting all unread emails

The code below permanently deletes all unread emails.

messages = server.search("UNSEEN")
for x in messages:
  server.delete_messages(x)
server.logout()

Permanently deleting all emails with a particular subject

We search the selected mailbox using our desired criteria. You should replace "Title" with your desired subject in the code below:

messages = server.search(['SUBJECT', 'Title'])
for x in messages:
  server.delete_messages(x)
server.logout()

Permanently deleting all emails from a specific sender

We search the mailbox using our desired criteria. It would be best if you replaced"abc@xyz.com" with your preferred email address in the code below:

messages = server.search(['FROM', 'abc@xyz.com'])
for x in messages:
  server.delete_messages(x)
server.logout()

Note

  • Logging out of the server is important
  • To access all emails while using IMAPlib, use mail.select('"[Gmail]/All Mail"').
  • Ensure you turn off less secure apps.
  • A lot of emails were harmed in the process of making this tutorial 😂.

Conclusion

I had fun writing this, and I hope you did too while reading it. I also encountered ERRORS while writing the script. The most recurring one was being unable to sign in even after following the instructions on the Google help page. This problem was encountered because I have more than one Gmail account signed in, and I was not using my default email. In case you encounter the same, the solution is outlined below:

  • The instruction said, "If the tips above didn't help, visit google.com/accounts/DisplayUnlockCaptcha and follow the steps on the page." This opens on a new tab.
  • The link on the new tab was "accounts.google.com/b/0/DisplayUnlockCaptcha" where the digit 0 is for the default account logged in.
  • Check your accounts in the order in which they are listed and change the digit accordingly (e.g.,”1" is the next email and so on).

You can find the complete script on GitHub below:

Thank you for reading this tutorial!

References