【问题标题】:Problems Listing Gmail Messages with User Created Label via Google API通过 Google API 列出带有用户创建标签的 Gmail 邮件时出现问题
【发布时间】:2020-05-25 08:31:02
【问题描述】:

我正在尝试使用 Gmail API 来阅读带有特定标签的邮件。主要目的是我希望能够通过 gmail 帐户在我的 iPhone 便笺应用程序中创建便笺(这基本上会生成一封自发送的电子邮件并在我的 Gmail 中将“便笺”标签放在上面)并自动检索/解析注意。

我已经能够通过 Python API 成功验证和访问我的帐户。我可以发送列出所有标签的请求,然后出现“注释”标签(以及其他用户创建的标签)。

当我遇到的问题是我无法检索带有用户创建的特定标签的邮件时。使用 Gmail API 文档中提供的代码,我可以成功地从任何默认标签(例如“草稿”、“未读”等)获取邮件。

对于用户创建的标签,我是否缺少一些我需要以不同方式做的事情?下面的代码是我正在使用的:

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)

这是我在尝试查询我创建的标签时得到的错误输出:

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

感谢您的帮助。如果我是一个相当新手的程序员,如果我遗漏了一些明显的东西,我深表歉意。

【问题讨论】:

标签: python python-3.x google-api gmail gmail-api


【解决方案1】:

每个标签都有一个名称和一个 ID。

对于默认标签,名称和 ID 是相同的,例如 用户创建的标签 THEY ARE NOT。

Users.messages: list 方法需要标签 ID,而不是标签名称

如果您不知道您的标签 ID 是什么 - list 您的标签 - 使用 Python 代码或 Try this API。结果将包含所有标签的名称和 ID。

示例:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-13
    • 2020-06-30
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 2015-10-26
    相关资源
    最近更新 更多