How can I print the subject and body of a GMail email using the python API?

半腔热情 提交于 2021-01-28 08:14:08

问题


    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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!