SaralGyaan, Saral Gyaan, Saral Gyan is website which provides free tutorials of Python for absolute beginners in English and Hindi, Learn Python in Hindi, Learn Python for absolute beginners, Learn Python, bootstrap, django, git

Hari S
Author: Hari S

Make Python delete your unwanted emails periodically.

Python की मदद से समय-समय पर अपने अवांछित ईमेलों को हटाएं

  • Jan. 9, 2019, 3:54 p.m.
  • 6 minutes read
Make Python delete your unwanted emails periodically.

There was a time when you will run to the mailbox outside your home at a fixed time and check your mail and segregate the crap out of it manually. But today, we all live in a digital era where the mail keeps on getting delivered to your electronic mailboxes throughout the day. All the mails received in your mailboxe are not important and there are tools like spam filters and unsubcribe optons to get rid of them. However, there are certain kinds of emails which do not exactly fall into the above two categories, one of the most common example is OTPs received from credit cards and banks. You won’t like to add them into your spambox or unsubscribe them.

If you are using a google mail account, google has come up with an API which can be seamlessly used with python to auto-delete your mails. Let’s walk through the steps one by one.

First of all visit

Login with the desired credentials and select a name for your project. python_gmail_api_integration_saralgyaan.png

Download Client Configuration will download the required ‘credentials.json’ file. Save it in a folder in which you are going to create the python script.


Now, we will use pip to download the desired modules i.e. google api and oauthclient

pip install --upgrade google-api-python-client oauth2client

Now time to create a python file and start coding. Let’s name it Just make sure that this script is created in the folder containing the ‘credentials.json’ file above. Since, we later will be hosting this script on PythonAnywhere and we need it to run in Python 3.6. Let’s add the shebang at the very top of it.


Now we will make the necessary imports.

import os
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from apiclient import errors

Since, we will be hosting this script on a cloud i.e. PythonAnywhere , it is better of to log the stuff to have some idea of what is going on daily. So quickly punch in the basic logging stuff. If it is bit overwhelming for you, just copy and paste it as soon we will be coming up with a basic tutorial on logging too.

import logging
logger = logging.getLogger(__name__)
formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')
file_handler = logging.FileHandler('auto_delete.log')

The script will be used to delete the email messages, so we need both read and write privileges. The same is called scope in terms of google email api

SCOPES = ''  # read-write mode

We will be needing a service to access our mailbox and since we will be using a function called ‘init’ to create the same, for now we will be setting it to none.


Create a function init, which will take three variables- user_id, token_file, credentials_file.

user_id : In all the cases we will be using ‘me’ as user_id which depicts the user for whom the credentials.json file has been downloaded in the steps above.

credentials_file: It is the ‘credentials.json’ downloaded above, note that this file must exist in the directory containing the script i.e. ‘’.

token_file: When the init function will be run for the very first time, it will open the browser and ask you to login to the desired gmail account(the one for which the ‘credentials.json’ file has been created.) and ‘token.json’ will be created in the same parent directory. If you ever change the ‘SCOPE’ defined above, you need to delete the token.json and re-generate the same.

def init(user_id='me', token_file='token.json', credentials_file='credentials.json'):

    global SERVICE

    if not os.path.exists(credentials_file):
        raise AutoDeleteException('Can\'t find credentials file at %s. You can download this file from and clicking "Enable the Gmail API"' % (os.path.abspath(credentials_file)))

    store = file.Storage(token_file)
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets(credentials_file, SCOPES)
        creds = tools.run_flow(flow, store)
    SERVICE = build('gmail', 'v1', http=creds.authorize(Http()))

In order to raise a custom exception in case of non missing ‘credentials.json’, we will be creating a class for that exception as under:-

class AutoDeleteException(Exception):

Now we will run the init() method using the following codes. If there is no error in the script, it will take you to the browser and ask you for the login credentials for which ‘credentials.json’ file was created. This will create a ‘token.json’ file in the same parent directory. Note that if you ever change the scope, you need to delete the ‘token.json’ and run init() again to re-create the ‘token.json’ file.

if __name__ == '__main__':

Now let’s create a search function with variables ‘query’ and user_id = ‘me’ to search for the messages matching the query.

The query will be set of queries as we will enter in the searchbox of gmail e.g.


for more details you can visit

Run the init() method to create the “SERVICE”

def search(query, user_id='me'):

    if SERVICE is None:

The following code will return a list of gmail thread objects matching the query. The gmail thread object is basically a dictionary with keys ‘id’ and ‘threadId’-

{'id': '15573cf1adfassafas', 'threadId': '15573cf1adfassafas'}

We will need the value of ‘id’ in our next function to delete the messages matching the query.

        response = SERVICE.users().messages().list(userId=user_id,
        messages = []
        if 'messages' in response:

        while 'nextPageToken' in response:
            page_token = response['nextPageToken']
            response = SERVICE.users().messages().list(userId=user_id, q=query,

        return messages

    except errors.HttpError as e:
        logger.exception(f'An error occurred:{e}')

So far so good, now create our last function to delete the messages matching the query. You must remember that this will permanently delete the message and won’t send it to the trash.So please use it with some caution.

def delete_messages(query, user_id='me'):
    messages = search(query)
    if messages:
        for message in messages:
            SERVICE.users().messages().delete(userId=user_id, id=message['id']).execute()
  'Message with id: {message["id"]} deleted successfully.')
    else:"There was no message matching the query.")

To run the script, let’s add the most loved dunders :P

if __name__ == '__main__':"Deleting messages from")
            subject:"Go Shopping"\

You can watch the entire tutorial on youtube too

Read this post to learn how to host the script on PythonAnywhere and schedule it to run daily.

Complete code for the same can be found at

Related Posts

Create a twitter bot using python and tweepy
By Hari S | 4 months, 3 weeks ago
Convert JSON to CSV using Python
By Hari S | 6 months ago


Mark Lorschy    Mark Lorschy:

HI Udit, I love the concept of your paper. Thank you. However, I am unable to delete emails from my gmail account. I followed your instructions to the letter. Any advise would be appreciated. Thank you

Hari S   Hari S:

Did you get any kind of error or something ? Check the log file if you created that. Because It worked like a charm for me.

3 weeks ago

You must confirm your email to reply.

Palvi Malik    Palvi Malik:

Gonna try it for sure. Thanks for the post.

Hari S   Hari S:

You are welcome

6 months, 2 weeks ago

You must confirm your email to reply.