简体   繁体   English

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

[英]How do I get body of every mails of my gmail account using gmail api?

I'm trying to parse each and every mail body from my gmail account using google oauth and gmail api services.我正在尝试使用 google oauth 和 gmail api 服务解析我的 gmail 帐户中的每个邮件正文。 As per now I can only get the messages id and thread id, when I open them it doesn't make sense at all.现在我只能得到消息 id 和线程 id,当我打开它们时它根本没有意义。 So the following code I have used that are as below:所以我使用的以下代码如下:

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()

and the output I got is like this for one of the message id using this line print(service.users().messages().get(userId='me', id='16931216e3a05048').execute())对于使用此行的消息 id 之一,我得到的输出是这样的print(service.users().messages().get(userId='me', id='16931216e3a05048').execute())

the output is like this:输出是这样的: 这是我使用上述代码得到的输出

You forgot to add the format你忘了添加格式

messages.get 消息.get

在此处输入图片说明

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM