【问题标题】:How do I get body of every mails of my gmail account using gmail api?如何使用 gmail api 获取我的 gmail 帐户的每封邮件的正文?
【发布时间】:2019-07-29 10:48:45
【问题描述】:

我正在尝试使用 google oauth 和 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='16931216e3a05048').execute())

输出是这样的:

【问题讨论】:

  • 我想要的是每封邮件的电子邮件正文,我们可以在其中获取我们需要的特定详细信息,例如我们如何知道该人是否订阅了该频道、博客或任何网站。我真的被困住了,我不只想要我现在收到的消息 sn-p。帮帮我

标签: python google-oauth gmail-api python-3.7 google-api-python-client


【解决方案1】:

你忘了添加格式

messages.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)

【讨论】:

  • 嘿兄弟,我不仅想要消息 sn-p,而且我得到的输出是这样的,上面有一些错误“消息 sn-p:嗨 AdityaMandal,来自 GeeksforGeeks 的问候!有你听说过 Python - The Programming Language 吗?如果是,那么我们为你准备了一个惊喜!如果你不知道,也不要感到沮丧”
  • 而我得到的错误是这样的 Traceback(最近一次调用最后一次):文件“C:\Users\sToNeR\Desktop\gmail\quickstart\quickstart.py”,第 56 行,在 main() 文件“C:\Users\sToNeR\Desktop\gmail\quickstart\quickstart.py”,第 42 行,在 main msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII' )) NameError: name 'base64' is not defined
  • 即使我忘记了像 bas64 和 email.mime.text 这样的模块,然后当我再次运行时,我收到如下消息 sn-p 但不是整个邮件正文并最终得到下面这个错误
  • Traceback(最近一次通话最后):文件“C:\Users\sToNeR\Desktop\gmail\quickstart\quickstart.py”,第 58 行,在 main() 文件“C: \Users\sToNeR\Desktop\gmail\quickstart\quickstart.py”,第 46 行,在 main mime_msg = email.message_from_string(msg_str) 文件“E:\Python 3\lib\email_init_.py ",第 38 行,在 message_from_string 中返回 Parser(*args, **kws).parsestr(s) 文件“E:\Python 3\lib\email\parser.py”,第 68 行,在 parsestr 中返回 self.parse(StringIO (text), headersonly=headersonly) TypeError: initial_value must be str or None, not bytes
猜你喜欢
  • 2016-12-12
  • 2016-09-28
  • 2016-07-26
  • 2019-06-21
  • 2021-04-20
  • 2016-07-30
  • 2018-05-18
  • 2016-12-16
  • 1970-01-01
相关资源
最近更新 更多