我正在尝试从gmailAPI读取访问代码,编码未获取完整/完整的消息正文。我正在使用Python代码

我尝试使用各种格式来获取完整的消息,例如Raw和Full

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帮助台。
谢谢,
Optum GovID

实际:
访问密码通知您要求一次性访问密码登录您的会员帐户。请在接下来的10分钟内输入以下访问代码,然后单击提交:您的一次性访问

注意:原始消息(预期)有很多空格,且e.t.c

最佳答案

回答:

您正在检索消息的摘要,而不是完整的消息正文。

说明及修正:

根据Gmail API的Users.messages资源文档,snippet是“邮件文本的一小部分”。为了获取完整的消息,您需要获取raw消息并对其进行解码,因为它在base64中返回。

在您的for循环中,您需要替换:

for message in messages:
    msg = service.users().messages().get(userId='me', id=message['id']).execute()
    print(msg['snippet'])


与:

for message in messages:
    msg = service.users().messages().get(userId='me', id=message['id']).execute()
    body = base64.b64decode(msg['raw'])
    print(body)


参考文献:


Users.messages Resource and methods

关于python - 无法使用Python对Gmail API进行全身按摩,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58464222/

10-14 19:10
查看更多