Python 如何使用gmail api获取我的gmail帐户的每封邮件的正文?

Python 如何使用gmail api获取我的gmail帐户的每封邮件的正文?,python,google-oauth,gmail-api,python-3.7,google-api-python-client,Python,Google Oauth,Gmail Api,Python 3.7,Google Api Python Client,我正在尝试使用GoogleOAuth和gmail api服务解析我的gmail帐户中的每个邮件正文。根据现在的情况,我只能得到消息id和线程id,当我打开它们时,这根本没有意义。 因此,我使用了以下代码,如下所示: from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow

我正在尝试使用GoogleOAuth和gmail api服务解析我的gmail帐户中的每个邮件正文。根据现在的情况,我只能得到消息id和线程id,当我打开它们时,这根本没有意义。 因此,我使用了以下代码,如下所示:

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

# 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()
        # 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()
    print(service.users().messages().list(userId='me').execute())
    print(service.users().messages().get(userId='me', id='16931216e3a05048').execute())
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name'])

if __name__ == '__main__':
    main()
对于一个消息id,我得到的输出是这样的,使用这一行
print(service.users().messages().get(userId='me',id='1693126e3a05048').execute())

输出如下:
您忘记添加格式了


嘿,兄弟,我不仅仅想要消息片段,而且我得到的输出是这样的,上面有一些错误“消息片段:嗨,阿迪蒂亚曼达尔,来自Geeksforgeks的问候!你听说过Python——编程语言吗?如果是的话,那么我们会给你一个惊喜!如果你不知道,不要感到沮丧”我得到的错误是这样的回溯(最后一次调用):文件“C:\Users\sToNeR\Desktop\gmail\quickstart\quickstart.py”,第56行,在main()文件“C:\Users\sToNeR\Desktop\gmail\quickstart\quickstart.py”,第42行,在main msg_str=base64.urlsafe\u b64解码(消息['raw']。编码('ASCII'))NameError:name'base64'未定义即使我忘了导入一些模块,如bas64和email.mime.text,但当我再次运行时,我得到的消息片段如下,但不是整个邮件正文,最后出现了以下错误回溯(上次最新调用):文件“C:\Users\sToNeR\Desktop\gmail\quickstart\quickstart.py”,第58行,在main()文件“C:\Users\sToNeR\Desktop\gmail\quickstart\quickstart.py”的第46行,在主mime_msg=email.message_from_string(msg_str)文件“E:\Python 3\lib\email_init.py”的第38行,在消息_from_string return Parser(*args,**kws)中。parsestr文件“E:\3\lib\email\Parser.py”的第68行,在parself.parse.parse中(StringIO(文本),headersonly=headersonly)TypeError:initial_值必须是str或None,而不是bytes我想要的是每封邮件的邮件正文,在那里我们可以得到我们需要的具体细节,比如我们如何知道这个人是否被转发到那个频道、博客或任何网站。我真的被卡住了,我不想要现在已经得到的消息片段。帮帮我吧
message = service.users().messages().get(userId=user_id, id=msg_id,
                                         format='raw').execute()

print 'Message snippet: %s' % message['snippet']

msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))

mime_msg = email.message_from_string(msg_str)