问题
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'])
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:
1. To make your coide less confusing it is recommended to call your messages as such rather than as labels:
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. 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)
}
]
}
This resource allows to access both body
, as well as subject
- the latter is contained in the message headers:
{
"name": string,
"value": string
}
However, those objects are not being returned with users.messages.list, but only with users.messages.get
Sample:
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)
来源:https://stackoverflow.com/questions/65459679/how-can-i-print-the-subject-and-body-of-a-gmail-email-using-the-python-api