Delete all unnecessary Gmail emails with API

I wrote a previous article, "Getting mail from the Gmail API using Python" (https://qiita.com/orikei/items/73dc1ccc95d1872ab1cf). As an extension of that, I tried to delete all past emails using API.

Operating environment

python3.8.3

API to use

We use an API called batchDelete. As a usage, you can delete all at once by passing the ID of the mail to be deleted to the request body as a list.

SCOPE changes

Specify SCOPE when connecting to the Gmail API. Last time, it was OK only for acquisition, so it was OK with Read Only, but this time it will be deleted, so it is necessary to change to SCOPE that can be fully accessed. Also, note that if you change SCOPE in the middle, you need to delete the'token.json'file. If you do not delete it, the changes will not be reflected. Reference: Choose Auth Scopes (from Gmail API page)

python


    def __init__(self):
        #If you change the Scope, token.To remove json
        self._SCOPES = 'https://mail.google.com/' #Specify full access SCOPE
        self.MessageIDList = []
        self.MessageList = []

    def ConnectGmail(self):
        #Connect to Gmail API
        store = file.Storage('token.json')
        creds = store.get()
        if not creds or creds.invalid:
            flow = client.flow_from_clientsecrets('credentials.json', self._SCOPES)
            creds = tools.run_flow(flow, store)
        service = build('gmail', 'v1', http=creds.authorize(Http()))
        
        return service

Source code

Actually, the deletion process is performed with the following source. ** * When you execute it, the mail is actually deleted, so please be careful about the conditions you specify. ** **

GmailAPI.py


from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import time

class GmailAPI:

    def __init__(self):
        # If modifying these scopes, delete the file token.json.
        self._SCOPES = 'https://mail.google.com/'
        self.MessageIDList = []

    def ConnectGmail(self):
        store = file.Storage('token.json')
        creds = store.get()
        if not creds or creds.invalid:
            flow = client.flow_from_clientsecrets('credentials.json', self._SCOPES)
            creds = tools.run_flow(flow, store)
        service = build('gmail', 'v1', http=creds.authorize(Http()))
        
        return service


    def DeleteMessageList(self,DateFrom,DateTo,MessageFrom):
        try:

            #Connect to API
            service = self.ConnectGmail()
            self.MessageIDList = []
            
            query = ''
            #Specify a search query
            if DateFrom != None and DateFrom !="":
                query += 'after:' + DateFrom + ' '
            if DateTo != None  and DateTo !="":
                query += 'before:' + DateTo + ' '
            if MessageFrom != None and MessageFrom !="":
                query += 'From:' + MessageFrom + ' '
            print("Deletion condition start date{0}End date{1} From:{2}".format(DateFrom,DateTo,MessageFrom))

            #Get a list of email IDs(Up to 500)
            self.MessageIDList = service.users().messages().list(userId='me',maxResults=500,q=query).execute()
            if self.MessageIDList['resultSizeEstimate'] == 0: 
                print("Message is not found")
                return False

            #Extract ID for batchDelete requestbody
            ids = {
                'ids': []
            }
            ids['ids'].extend([str(d['id']) for d in self.MessageIDList['messages']])
            
            #Delete process
            print("{0}Delete processing started".format(len(ids['ids'])))
            service.users().messages().batchDelete(userId='me',body=ids).execute()
            print("Deletion completed")

            return True
    
        except Exception as e:
            print("An error has occurred")
            print(e)
            return False

if __name__ == '__main__':

    gmail = GmailAPI()

    #Since there is a limit to the number of items that can be deleted at one time, iteratively processes until the target data is exhausted.
    for i in range(100):
        #Call the deletion process by specifying arbitrary conditions (period and From address)
        if (gmail.DeleteMessageList(DateFrom='2010-01-01',DateTo='2020-10-30',MessageFrom='[email protected]') == False):
            break
        if len(gmail.MessageIDList['messages']) < 500:
            #Exit the process
            break
        else:
            #Wait 10 seconds
            time.sleep(10)

in conclusion

I tried to delete the mail using API. I think it's easier than deleting it with the Gmail GUI, so I hope you can refer to it.

Recommended Posts

Delete all unnecessary Gmail emails with API
Easily send emails with Gmail with Django
Get Gmail subject and body with Python and Gmail API
Delete all Readability bookmarks
Extrude with Fusion360 API
Delete all Docker Volumes
Delete all libraries installed on pip with a single command