如何使用python API打印GMail电子邮件的主题和正文?
问题描述:
results = service.users().messages().list(
userId='me', labelIds=['INBOX'], maxResults=1).execute()
labels = results.get('messages', [])
if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
print(label['id'])
此脚本打印最新电子邮件的消息ID.如何打印电子邮件的主题和正文?我找不到任何操作方法的文档
This script prints the message Id of the most recent email. How can I print the subject and body of the emails? I can't find any documentation on how to do it
答
1.为了减少混乱,建议您以这样的方式而不是标签方式来呼叫消息:
results = service.users().messages().list(
userId='me', labelIds=['INBOX'], maxResults=1).execute()
messages = results.get('messages', [])
if not messages:
print('No messages found.')
else:
print('Messages:')
for message in messages:
print(message['id'])
2.看看消息资源:
2. Have a look at the message resource:
{
"id": string,
"threadId": string,
"labelIds": [
string
],
"snippet": string,
"historyId": string,
"internalDate": string,
"payload": {
object (MessagePart)
},
"sizeEstimate": integer,
"raw": string
}
payload
includes the object MessagePart, that contains the following nested objects:
{
"partId": string,
"mimeType": string,
"filename": string,
"headers": [
{
object (Header)
}
],
"body": {
object (MessagePartBody)
},
"parts": [
{
object (MessagePart)
}
]
}
此资源允许同时访问 body
和 subject
-后者包含在消息
This resource allows to access both body
, as well as subject
- the latter is contained in the message headers:
{
"name": string,
"value": string
}
但是,这些对象不会返回users.messages.list ,但只能使用 users.messages.get
However, those objects are not being returned with users.messages.list, but only with users.messages.get
示例:
results = service.users().messages().list(
userId='me', labelIds=['INBOX'], maxResults=1).execute()
messages = results.get('messages', [])
if not messages:
print('No messages found.')
else:
print('Messages:')
for message in messages:
print(message['id'])
messageResource = service.users().messages().get(userId="me",id=message['id']).execute()
headers=messageResource["payload"]["headers"]
subject= [j['value'] for j in headers if j["name"]=="Subject"]
print(subject)