[英]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
正如在这个答案中提到的,主题在
payload
的headers
"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.