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)