Declutter your Gmail Inbox with Python

Using ezgmail to automate the process of reading and deleting emails

Alberta Odamea Anim-Ayeko
Towards Data Science

--

Photo by Stephen Phillips — Hostreviews.co.uk on Unsplash

Introduction

Having to manually delete emails one after another in the gmail app is definitely not a good use of your time, especially when you can automate the process. In this article, I will show you how to automate the process of deleting unwanted emails and marking emails as read. This way you can have a program do it for you, while you do an important task or catch up on your favourite tv show 😉.

It was only moments ago that I discovered the ezgmail python package created by Al Sweigart, and I think its functions are pretty simple as compared to some others that I have seen before.

Requirements

  • A python version installed on your PC. If you don’t have python installed, follow the instructions here to do so.
  • An ide of your choice. Jupyter notebook, spyder, pycharm, etc.
  • The ezgmail package installed, which you can do by running pip install EZgmail in your terminal

Setting up your gmail developer account

You cannot skip this step, otherwise the ezgmail package will not work. This part is quite lengthy but totally worth it when you get to the end.

  • Create a new folder where you would work in. ezgmail_python is a good choice.
  • Click here and sign in with your gmail account.
  • Follow Step 1 on the page by running:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Follow Step 2 on the page by creating the quickstart.py file and add the code in step 2 into the file.

  • Save the quickstart.py in the folder you created at the start. The ezgmail_python folder
  • DO NOT run python quickstart.py as said on the page!
  • Click here and log in if you have to.
  • Click Select a project -> New Project -> Enter a Project name in the field provided(Eg: ezgmail)The Location field can be ignored
  • Click CREATE
  • Select your ezgmail project from the notification popup. You will be sent to the following page:
Dashboard for the ezgmail project
  • On the left pane of the screen, click on APIs & Services -> OAuth consent screen as seen in the image below:
Choosing the OAuth consent screen option
  • From the OAuth consent screen shown, click the external option and click create as seen in the screen below:
Choosing the ‘external’ option for the user type
  • There is an Edit app registration form that appears next. Fill in the following fields:

— App Information

  • App name = ezgmail
  • User support email = your own gmail
  • App logo can be ignored

— App domain

  • Ignore all fields here as they are not compulsory

— Authorized domains

  • Ignore this section

— Developer contact information

  • Enter your own email here

Click save and continue

Ignore the next section, which is the about the scopes of your app.

Click save and continue

For the next section, which is the Test Users section, Click on +Add Users button and add your own email address, click add

Click save and continue

After that, you a provided a summary of all the data you provided, if everything looks okay, click BACK TO DASHBOARD

Now, click on the Credentials option on the left part of the screen, and you will be shown the following:

The create credentials page

Click the+CREATE CREDENTIALS option above, then choose the OAuth Client ID option. From the Application type drop down, select the Desktop App option, you can leave the name as it is. Click CREATE. The expected screen is seen below:

The Create OAuth client ID page

There is another popup which appears after hitting the CREATE button which shows your credentials; Your Client ID and Client Secret. Make sure not to share these with anyone. Download these credentials by clicking the DOWNLOAD JSON button. Be sure to rename the file as credentials.json and save in the ezgmail_python folder you created at the beginning.

Working with the ezgmail package

I strongly recommend that the following commands are run in a terminal and not in your ide.

Move into your ezgmail_python folder by using the cd command. Run the following:

python->Running this enables you to start writing python code in the terminal

import ezgmail->Upon running this, a window is opened in your browser, asking you to chose the email account you wish to give access, to your application. Choose your own email which you want to declutter. Then you are met with another page telling you that the app isn’t verified and whether you want to continue or not. Click continue

The google warning page about app verification

Click continue again to ensure that you give ezgmail access to your google account. There is a page which says: The authentication flow has completed. You would also realize there is a new file called token.json in your ezgmail_python folder after a successful authentication.

Commands run in the terminal

If the import ezgmail step above doesn’t work, try ezgmail.init()

Whew😅, you’re all set! Using the functions introduced below are as easy as ABC. Ready to experience the magic?

Marking emails as read

The following codes can now be run in your ide and not in the terminal.

unreadThreads = ezgmail.unread(maxResults=300)
print(f'There are {len(unreadThreads)} unread emails in your account')
for unread in unreadThreads:
print(ezgmail.summary(unread), ‘\n’)
unread.markAsRead()

It’s that simple! 😲In the 1st line of the code snippet above, you can change the maxResults argument to any number of your choice, as it controls the number of unread emails returned. From there, the actual number of unread emails in your inbox is returned and printed to your screen. The 4th line returns a summary of the body of your unread emails, and in the last line, these emails are marked as read by the program.

Deleting emails

For email deletion, you must be very sure, before you proceed. The following code helps you to do the deletion.

  • Deleting emails by looking up (a) keyword(s)
keywords = ['LinkedIn', 'Cesium Forum', 'ASOS']
for keyword in keywords:
threads = ezgmail.search(keyword, maxResults=300)
print(f’There are {len(threads)} emails with the keyword, {keyword}’)
ezgmail.summary(threads) #You can check a summary just to make sure you’re not deleting anything important
for i in range(len(threads)):
if len(threads)==0:
print(‘No \’{keyword}\’ messages to delete, moving on to the next’)
else:
threads[i].trash()

The list of keywords above should be replaced by those of interest to you, and they can be as many words as you’d like. Iterating through the keywords list with a for loop, ezgmail searches for each of the your emails that contain those particular keywords, and returns them. And for each of the keyword threads, the number of emails present are counted, before they are finally deleted.

Don’t panic if you realize you have deleted something important, you can find deleted emails in the bin of the gmail app.

  • Deleting recent emails
threads = ezgmail.recent(maxResults=20)
print(f’There are {len(threads)} recent emails in your inbox’)
ezgmail.summary(threads) #You can check a summary just to make sure you’re not deleting anything important
for i in range(len(threads)):
if len(threads)==0:
print(‘No recent emails')
else:
threads[i].trash()

Having introduced the recent function and the keyword concept, it can also be used to mark emails as read, if you think that is a safer option.

Parting thoughts

There are other ezgmail functions you can play with like re (used for regular expressions), which can help you look for specific patterns in emails before proceeding to mark as read or delete. It is worth exploring. I hope after going through this article, you adopt some of these ways of cleaning out your inbox. Thanks for reading! 👋🏾

Sources

Ezgmail documentation

--

--