0

I am trying to use the Gmail API to read messages with a specific label. The main purpose is that I want to be able to create notes in my iPhone Notes app via gmail account (this generates essentially a self-sent email and puts a "Notes" label on it in my Gmail) and automate retrieval/parsing of the note.

I've been able to successfully authenticate and access my account through the Python API. I can send requests to list all labels and the "Notes" label (as well as other user-created labels) appear.

When the problem I'm having is that I'm unable to retrieve messages with a specific label that was user created. Using the code provided in the Gmail API docs, I can successfully get messages from any of the default labels (e.g. "DRAFT", "UNREAD", etc..).

Is there something I'm missing about user-created labels that I need to do differently? The below code is what I'm using:

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient import errors

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

def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    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 available, 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(
                'credentials.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)
    service = build('gmail', 'v1', credentials=creds)

    # Call the Gmail API
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name'])

    return service
def ListMessagesWithLabels(service, user_id,label_ids=[]):
try:
    response = service.users().messages().list(userId=user_id, labelIds=label_ids).execute()
    messages = []

    if 'messages' in response:
        messages.extend(response['messages'])

    while 'nextPageToken' in response:
        page_token = response['nextPageToken']
        response = service.users().messages().list(userId=user_id,labelIds=label_ids,pageToken=page_token).execute()

        messages.extend(response['messages'])

    return messages
except errors.HttpError as error:
    print (f'An error occurred: {error}')

if __name__ == '__main__':
    service = main()

messages1 = ListMessagesWithLabels(service, 'me',["Receipts"])

for message in messages1:
    print(message)

And this is the error output I get when trying to query a label that I created:

An error occurred: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages?labelIds=Receipts&alt=json returned "Invalid label: Receipts">
Traceback (most recent call last):

  File "/Users/alec/GmailAPI/quickstart.py", line 86, in <module>
    for message in messages1:

TypeError: 'NoneType' object is not iterable

Thanks for any help. Apologies if I'm missing something obvious as I'm a fairly novice programmer.

ac1256
  • 3
  • 2

1 Answers1

0

Every label has a name and an Id.

For the default labels the names and Ids are identical, for user-created label THEY ARE NOT.

The method Users.messages: list expects a label Id, not a label name.

If you do not know what your label Id is - list your labels - either with Python code or with the Try this API. The result will contain the names and Ids of all your labels.

Sample:

enter image description here

ziganotschka
  • 25,866
  • 2
  • 16
  • 33