简体   繁体   English

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

[英]Python: how to get the subject of an email from gmail API

Using Gmail API, how can I retrieve the subject of an email?使用 Gmail 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.我在原始文件中看到它,但检索它很麻烦,我相信应该有一种方法可以直接通过 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正如在这个答案中提到的,主题在payloadheaders

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

But this not available if you use format="raw ".但是,如果您使用format="raw ",则此方法不可用。 So you need to use format="full" .所以你需要使用format="full"

Here is a full code:这是一个完整的代码:

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

Since this was the question I landed on, I just wanted to share what I found to solve my own issue.由于这是我遇到的问题,我只想分享我发现的解决我自己问题的方法。

I am used to work with the email module that gives you a neat interface to interact with messages.我习惯于使用email模块,该模块为您提供了一个与消息交互的简洁界面。 In order to parse the message that the gmail api gives you, the following worked for me:为了解析 gmail api 给你的消息,以下对我有用:

import email
import base64
messageraw = service.users().messages().get(
    userId="me", 
    id=emails["id"], 
    format="raw", 
    metadataHeaders=None
).execute()
email_message = email.message_from_bytes(
    base64.urlsafe_b64decode(messageraw['raw'])
)

You end up with an email.Message object and can access the metadata like email_message['from'] .您最终会得到一个email.Message对象,并且可以访问像email_message['from']这样的元数据。

with this code reads all the content of the mail使用此代码读取邮件的所有内容

resultado = service.users().messages().list(userId= 'me',q=q_str,labelIds= ['INBOX']).execute()
mensajes = resultado.get('messages', [])
print ("Mensaje:")
    for mensaje in mensajes[:1]:
        leer = service.users().messages().get(userId='me', id=mensaje['id']).execute()
        payload = leer.get("payload")
        header = payload.get("headers")
        for x in header:
            if x['name'] == 'subject':
                sub = x['value'] #subject
                print(sub)
        print(leer['snippet'])  #body

q=q_str , this is the filter. q=q_str ,这是过滤器。 view the API documentation.查看 API 文档。

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

相关问题 如何从python中的gmail下载特定主题和日期的电子邮件附件 - how to download an email attachment from gmail in python for a particular subject and date 通过 Python 中的 Gmail API 获取给定日期之间的电子邮件列表(发件人的电子邮件、主题和正文) - Get list of emails (Sender's Email, Subject and Body) between given dates through Gmail API in Python 适用于Gmail /主题的python电子邮件模块 - python email module for Gmail / subject 如何使用 python ZDB974238714CA8DE634A7CE1D0F 打印 GMail email 的主题和正文? - How can I print the subject and body of a GMail email using the python API? Python和GMail-将来自具有指定主题的指定帐户的电子邮件标记为已读 - Python and GMail - Mark email from specified account with defined subject as read 如何从python中的email主题分析得到主要上下文 - How to analyze and get the main context from email subject in python 您如何获得 email gmail python API 的收件人 - How can you get the recipients of an email gmail python API 如何获取电子邮件 gmail python API 的发件人 - How can I get the sender of an email gmail python API Python 中的正则表达式从 email 获取主题文本 - Regex in Python to get the subject text from an email Python Gmail Api:电子邮件未按指定发送 - Python Gmail Api: Email is not sending as the specified from
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM