Python:如何从gmail API获取电子邮件的主题 [英] Python: how to get the subject of an email from gmail API

查看:110
本文介绍了Python:如何从gmail API获取电子邮件的主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using Gmail API, how can I retrieve the subject of an email?

我在原始文件中看到了它,但是检索它很麻烦,而且我相信应该有一种直接通过API进行操作的方法。

I see it in the raw file but it's qui cumbersome to retrieve it, and I am sure there should be a way to do it directly via the API.

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

是相同的这样的问题一个,但是它已经很接近了,所以我无法提供比提出的更好的答案。

It is the same question as this one but it has been close even so I can't post a better answer than the one proposed.

推荐答案

如此答案中所述,主题位于标题的标题中

As mentionned in this answer, the subject is in the headers from payload

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

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

But this not available if you use format="raw". So you need to use 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获取电子邮件的主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆