skip to Main Content

how to get the first message of a particular user(like facebook’s first message to me) using using gmail api

currently i’m using this code to get all the messages

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

SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'

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',maxResults=20,labelIds = ['INBOX']).execute()
messages = results.get('messages', [])

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

if __name__ == '__main__':
    main()

2

Answers


  1. By looking at your code, I think you need to replace below code snippet

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

    with following code snippet,

    msg = service.users().messages().get(userId='me', id=messages[-1]['id']).execute()
    print(msg['snippet'])
    
    Login or Signup to reply.
  2. Get the length of messages :

    last_index = len(messages) - 1
    
    msg = service.users().messages().get(userId='me', id=messages[last_index]['id']).execute()
    print(msg['snippet'])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search