[PYTHON] Use API to mark a large number of unread emails in Gmail as read

Last time wrote how to delete all at once, but this time I will write about how to mark it as read.

Operating environment

python3.8.3

API to use

We use an API called batchModify. As a usage, you can change all at once by setting the ID of the email to be deleted and the changed contents (this time, remove the unread label) in the request body.

requestbody


            {
                'ids': [],
                "removeLabelIds": [
                "UNREAD"
                ]
            }

filter added

When I first search for emails, I add a condition so that only unread emails can be pulled.

python


            #Specify a search query
            query += 'is:unread ' #Unread only

Source code

Actually, the update process is performed with the following sources.

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 ModifyUnreadMessageList(self,DateFrom,DateTo,MessageFrom):
        try:

            #Connect to API
            service = self.ConnectGmail()
            self.MessageIDList = []
            
            query = ''
            #Specify a search query
            query += 'is:unread ' #Unread only
            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("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 batchModify requestbody
            ids = {
                'ids': [],
                "removeLabelIds": [
                "UNREAD"
                ]
            }
            ids['ids'].extend([str(d['id']) for d in self.MessageIDList['messages']])
            
            #Update process
            print()
            print("{0}Read update start".format(len(ids['ids'])))
            service.users().messages().batchModify(userId='me',body=ids).execute()
            print("Update 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, repeat until the target data is exhausted.
    for i in range(100):
        if (gmail.ModifyUnreadMessageList(DateFrom='2000-01-01',DateTo='2020-11-30',MessageFrom=None) == False):
            break
        if len(gmail.MessageIDList['messages']) < 500:
            #Exit the process
            break
        else:
            #Wait 10 seconds
            time.sleep(10)

in conclusion

I was able to mark it as read in bulk using the API. If you have a large amount of unread mail, you can update it faster than operating it from the GUI, so please take advantage of it.

Recommended Posts

Use API to mark a large number of unread emails in Gmail as read
Upload a large number of images to Wordpress
TensorFlow To learn from a large number of images ... ~ (almost) solution ~
Convert a large number of PDF files to text files using pdfminer
How to create a large amount of test data in MySQL? ??
Use shutil to delete all folders with a small number of files
[Python] How to put any number of standard inputs in a list
TensorFlow To learn from a large number of images ... (Unsolved problem) → 12/18 Solved
Various ways to read the last line of a csv file in Python
One-liner to create a large number of test files at once on Linux
Set the number of elements in a NumPy one-dimensional array to a power of 2 (0 padded)
I made a Line Bot that uses Python to retrieve unread Gmail emails!
How to count the number of elements in Django and output to a template
How to read a serial number file in a loop, process it, and graph it
Summary of how to use MNIST in Python
Find the number of days in a month
Organize a large number of files into folders
How to create a Rest Api in Django
How to read a file in a different directory
How to identify the element with the smallest number of characters in a Python list?
Consolidate a large number of CSV files in folders with python (data without header)
I want to use a network defined by myself in PPO2 of Stable Baselines
Use slackbot as a relay and return from bottle to slack in json format.
A tool to follow posters with a large number of likes on instagram [25 minutes to 1 second]
Find a guideline for the number of processes / threads to set in the application server
How to use python multiprocessing (continued 3) apply_async in class with Pool as a member
Create a dataset of images to use for learning
Accelerate a large number of simple queries with MySQL
A memo of how to use AIST supercomputer ABCI
A memorandum on how to use keras.preprocessing.image in Keras
Convenient to use matplotlib subplots in a for statement
Read a large amount of securities reports using COTOHA
2 ways to read all csv files in a folder
Use date to x-axis of tsplot depicted in seaborn
[Python] Randomly generate a large number of English names
[Python] Programming to find the number of a in a character string that repeats a specified number of times.