不使用Python获取Gmail API的全文消息
我试图从gmailAPI中读取访问代码,coded并没有获取完整的消息体。我正在使用Python代码 我尝试使用各种格式来获取完整的消息,如原始和完整消息不使用Python获取Gmail API的全文消息,python,gmail-api,google-api-python-client,Python,Gmail Api,Google Api Python Client,我试图从gmailAPI中读取访问代码,coded并没有获取完整的消息体。我正在使用Python代码 我尝试使用各种格式来获取完整的消息,如原始和完整消息 from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from g
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import dateutil.parser as parser
from bs4 import BeautifulSoup
import base64
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
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)
results = service.users().messages().list(userId='me',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()
预期结果:您请求了一次性访问代码以登录到您的成员帐户。请在接下来的10分钟内输入以下访问代码,然后单击提交:
您的一次性访问代码:8627816
这是一封自动邮件。请不要回复此邮件。如果您有任何问题,请联系Optum GovID IT帮助台。
非常感谢。
戈维德眼
实际:
访问代码通知您请求了一次性访问代码以登录到您的会员帐户。请在接下来的10分钟内输入以下访问代码,然后单击提交:您的一次性访问
注意:原始消息(预期)有许多空格和e.t.c答案:
您正在检索消息的一个片段,而不是完整的消息正文
解释和修复:
根据Gmail API的Users.messages资源文档,代码片段是“消息文本的一小部分”。为了获取完整的消息,您需要获取raw
消息,并在base64
中返回时对其进行解码
在for
循环中,您需要替换:
对于消息中的消息:
msg=service.users().messages().get(userId='me',id=message['id']).execute()
打印(msg['snippet'])
与:
对于消息中的消息:
msg=service.users().messages().get(userId='me',id=message['id']).execute()
body=base64.b64解码(msg['raw'])
印刷品(正文)
参考资料:
msg['snippet']
我怀疑这会返回完整的消息文本。@OMMSE2etsGovID很乐意帮忙!出于文档目的,如果可以的话,请接受对您有帮助的答案-这也有助于将来遇到相同问题的其他人找到解决方案:)