D
D
Danila Rumyantsev2022-04-19 21:19:39
Python
Danila Rumyantsev, 2022-04-19 21:19:39

How to remove 500 results limit in gmailAPI for python?

I'm planning to write a program that counts the number of sent and received messages on a certain day, but I can't find how to remove the limit in maxResults, large values ​​don't help.

from __future__ import print_function
import pprint
import os.path
import pickle

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']


def gmail_authenticate():
    creds = None
    # the file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first time
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # if there are no (valid) credentials availablle, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('client.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)
    return build('gmail', 'v1', credentials=creds)

# get the Gmail API service
service = gmail_authenticate()
msgs = service.users().messages().list(userId='me',maxResults=50000).execute()


for msg in msgs['messages']:
    m_id = msg['id'] # get id of individual message
    message = service.users().messages().get(userId='me', id=m_id).execute()
    payload = message['payload']
    header = payload['headers']
    #print(header[0]['name'],' '.join(header[1]['value'].split()[6:11]))
    print(header[0]['name'],header[1]['value'])

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2022-04-19
@Bubunduc

No, Google's limitation. You receive 500 messages, get the next page token from the response, call this method again, adding a parameter pageTokenwith the value you received.
something like this

messages = []
next_page_token = None

for _ in range(3):
    if next_page_token:
        msgs = service.users().messages().list(userId='me',maxResults=500, pageToken=next_page_token).execute()
    else:
        msgs = service.users().messages().list(userId='me',maxResults=500).execute()

    messages.extend(msgs)
    next_page_token = msgs['nextPageToken']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question