python - Python:如何从 gmail API 获取电子邮件的主题
问题描述
使用 Gmail API,我如何检索电子邮件的主题?
我在原始文件中看到它,但检索它很麻烦,我相信应该有一种方法可以直接通过 API 来完成。
messageraw= service.users().messages().get(userId="me", id=emails["id"], format="raw", metadataHeaders=None).execute()
这与这个问题相同,但它已经很接近了,所以我无法发布比提出的问题更好的答案。
解决方案
正如这个答案中提到的那样,主题是headers
从payload
"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()
推荐阅读
- c# - 通过 dapper 动态参数将 int 列表发送到 sql sp
- django - /admin/accounts/user/1/change/ 'User' 对象的 AttributeError 没有属性 'profile'
- jquery - Ideal Forms 3 自定义正则表达式验证
- docker - 为什么 docker 容器的行为不同?
- excel - 带有匹配和不匹配的 Vlookup 返回 VBA 中的特定值。请找到以下代码。我需要知道如何获得匹配值
- python - 使用主脚本中的变量调用基本脚本的主 python 脚本
- azure - 无法使用 ARM 在应用服务计划上创建基于 Windows (OS) 的函数应用
- node.js - AWB Elastic Beanstalk 一些请求没有返回响应
- scala - 创建火花会话时出现 NoSuchMethodError
- laravel - 如何在 laravel 5.5 中从数据库中进行搜索