Last time wrote how to delete all at once, but this time I will write about how to mark it as read.
python3.8.3
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"
                ]
            }
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
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)
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