Read last 20 messages using GMAIL API

I have been trying to get data to read message from Gmail API .

It's working fine but how to limit this code to get only last 20 messages. Not all the messages.

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


def main():

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

    # Call the Gmail API to fetch INBOX
    results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
    messages = results.get('messages', [])

    if not messages:
        print("No messages found.")
        print("Message snippets:")
        for message in messages:
            msg = service.users().messages().get(userId='me', id=message['id']).execute()

if __name__ == '__main__':


Just add this add while calling the GMAIL API to fetch inbox.

results = service.users().messages().list(userId='me',maxResults=20,labelIds = ['INBOX']).execute()

2 answers

  • answered 2019-01-11 05:54 Alderven

    Update this code:

    for message in messages:
        msg = service.users().messages().get(userId='me', id=message['id']).execute()
        print (msg['snippet'])

    with this:

    for i, message in enumerate(messages):
        if i == 20:
        msg = service.users().messages().get(userId='me', id=message['id']).execute()
        print (msg['snippet'])

  • answered 2019-01-11 05:55 Sabesh

    Try the pagination concept provided by the google API to limit the messages returned in the response. Here's the official Documentation

    Some API methods may return very large lists of data. To reduce the response size, many of these API methods support pagination. With paginated results, your application can iteratively request and process large lists one page at a time. For API methods that support it, there exist similarly named methods with a "_next" suffix. For example, if a method is named list(), there may also be a method named list_next().

    You have to do
    messages = results.get_next('messages', [])