根据下面引用的文档,消息应包含一个消息部分,该消息部分应再包含一个消息部分正文。
我该如何使用这个API获取消息的实际正文内容?
https://developers.google.com/gmail/api/reference/rest/v1/users.messages#Message
当我运行下面的代码(这只是一个修改过的样本脚本,可以在这里找到,其中消息被替换为标签)时from __future__ import print_function
import pickle
import os.path
import openpyxl
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://mail.google.com/']
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().messages().list(userId='me').execute()
messages = results.get('messages', [])
if not messages:
print('No messages found.')
else:
print('Messages:')
for message in messages:
print(message)
if __name__ == '__main__':
main()
我只得到了消息ID和线程ID,例如:
Messages:
{'id': '177045ba844e1991', 'threadId': '177045ba844e1991'}
{'id': '1770415ccdd222d7', 'threadId': '1770415ccdd222d7'}
{'id': '17703970573550eb', 'threadId': '17703970573550eb'}
{'id': '177031073928a223', 'threadId': '177031073928a223'}
{'id': '17702de505951773', 'threadId': '17702de505951773'}
{'id': '17702a3e6d1893de', 'threadId': '17702a3e6d1893de'}
我该如何使用这个API获取消息的实际正文内容?
main
函数内部。add
函数是一个回调函数。以batch = ...
开头的代码位于add
函数之外,只是main
函数的一部分(因此实际上并没有使用自身)。生成的带有正文的消息将存储在messages
中,可以根据需要进行使用。例如,您可以像在问题中那样打印它们(相同的6行代码应该能够工作)。 - Martí