通过 Google API 使用用户创建的标签列出 Gmail 邮件时出现问题
Problems Listing Gmail Messages with User Created Label via Google API
我正在尝试使用 Gmail API 阅读带有特定标签的邮件。主要目的是我希望能够通过 gmail 帐户在我的 iPhone Notes 应用程序中创建笔记(这实际上会生成一封自发电子邮件,并在我的 Gmail 中放置一个 "Notes" 标签)和自动化笔记的 retrieval/parsing。
我已经能够通过 Python API 成功验证和访问我的帐户。我可以发送请求以列出所有标签,然后出现 "Notes" 标签(以及其他用户创建的标签)。
当我遇到的问题是我无法检索带有用户创建的特定标签的邮件时。使用 Gmail API 文档中提供的代码,我可以成功地从任何默认标签(例如 "DRAFT"、"UNREAD" 等)获取邮件。
关于用户创建的标签,我是否遗漏了一些我需要以不同方式做的事情?下面的代码是我正在使用的:
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
感谢您的帮助。如果我遗漏了一些明显的东西,我深表歉意,因为我是一个相当新手的程序员。
每个标签都有一个名称和一个 Id。
For the default labels the names and Ids are identical, for
user-created label THEY ARE NOT.
方法 Users.messages: list 需要 标签 ID,而不是标签名称。
如果您不知道您的标签 ID 是什么 - list 您的标签 - 使用 Python 代码或 Try this API
。结果将包含所有标签的名称和 ID。
样本:
我正在尝试使用 Gmail API 阅读带有特定标签的邮件。主要目的是我希望能够通过 gmail 帐户在我的 iPhone Notes 应用程序中创建笔记(这实际上会生成一封自发电子邮件,并在我的 Gmail 中放置一个 "Notes" 标签)和自动化笔记的 retrieval/parsing。
我已经能够通过 Python API 成功验证和访问我的帐户。我可以发送请求以列出所有标签,然后出现 "Notes" 标签(以及其他用户创建的标签)。
当我遇到的问题是我无法检索带有用户创建的特定标签的邮件时。使用 Gmail API 文档中提供的代码,我可以成功地从任何默认标签(例如 "DRAFT"、"UNREAD" 等)获取邮件。
关于用户创建的标签,我是否遗漏了一些我需要以不同方式做的事情?下面的代码是我正在使用的:
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
感谢您的帮助。如果我遗漏了一些明显的东西,我深表歉意,因为我是一个相当新手的程序员。
每个标签都有一个名称和一个 Id。
For the default labels the names and Ids are identical, for user-created label THEY ARE NOT.
方法 Users.messages: list 需要 标签 ID,而不是标签名称。
如果您不知道您的标签 ID 是什么 - list 您的标签 - 使用 Python 代码或 Try this API
。结果将包含所有标签的名称和 ID。
样本: