Python:如何从 gmail API 获取电子邮件的主题

标签 python python-3.x email gmail-api

如何使用 Gmail API 检索电子邮件的主题?

我在原始文件中看到它,但检索它非常麻烦,而且我确信应该有一种方法可以直接通过 API 进行检索。

messageraw= service.users().messages().get(userId="me", id=emails["id"], format="raw", metadataHeaders=None).execute()

这是同一个问题one但它已经很接近了,所以我无法发布比提议的更好的答案。

最佳答案

如本 answer 中所述,主题位于 payload

headers
 "payload": {
    "partId": string,
    "mimeType": string,
    "filename": string,
    "headers": [
      {
        "name": string,
        "value": string
      }
    ],

但如果您使用 format="raw",则此功能不可用。所以你需要使用format="full"

完整代码如下:

# source  = https://developers.google.com/gmail/api/quickstart/python?authuser=2


# connect to gmail api 
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():

    # create the credential the first time and save it in token.pickle
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    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()
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    #create the service 
    service = build('gmail', 'v1', credentials=creds)

    #*************************************
    # ressources for *get* email 
    # https://developers.google.com/resources/api-libraries/documentation/gmail/v1/python/latest/gmail_v1.users.messages.html#get
    # code example for decode https://developers.google.com/gmail/api/v1/reference/users/messages/get 
    #*************************************

    messageheader= service.users().messages().get(userId="me", id=emails["id"], format="full", metadataHeaders=None).execute()
    # print(messageheader)
    headers=messageheader["payload"]["headers"]
    subject= [i['value'] for i in headers if i["name"]=="Subject"]
    print(subject)  

if __name__ == '__main__':
    main()

关于Python:如何从 gmail API 获取电子邮件的主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144261/

相关文章:

python - py2exe:减少库存档的大小

python - Jinja for 循环范围在递增变量时被重置

python - 如何使用 Python 临时将文件夹添加到 Windows PATH?

python - 如何根据 CPU 的限制处理多进程

email - Outlook 从电子邮件中去除 URL 哈希

iphone - iPhone 的邮件发送框架

python - 如何缩放除最后一列之外的所有列?

python - 开始对没有返回值的函数进行单元测试

python - 使用 if else 逻辑应用函数修改多列

ruby-on-rails - 将 i18n gem 与邮件一起使用时出现问题