Search code examples
emailgoogle-apigmailgmail-api

Getting specific headers along with other body data in Users.thread: get


You can very easily select what headers you want in a Users.thread: get-request, like so:

format = metadata
metadataHeaders = From

GET https://www.googleapis.com/gmail/v1/users/me/threads/14eaffaf5e3e8242?metadataHeaders=From&format=metadata&key={YOUR_API_KEY}

Response:

{
 "id": "14eaffaf5e3e8242",
 "historyId": "510358",
 "messages": [
  {
   "id": "14eaffaf5e3e8242",
   "threadId": "14eaffaf5e3e8242",
   "labelIds": [
    "SENT",
    "INBOX",
    "IMPORTANT"
   ],
   "snippet": "Wow Emil!",
   "historyId": "510292",
   "internalDate": "1437471536000",
   "payload": {
    "mimeType": "multipart/mixed",
    "headers": [
     {
      "name": "From", // I just got the header I asked for.
      "value": "Emil Tholin <[email protected]>"
     }
    ]
   },
   "sizeEstimate": 9260
  }, ...
}

You can also get certain parts of the body very easily. E.g. here I ask for the attachmentIds of all the attachments in the message body:

field = messages/id,messages/payload/parts/body/attachmentId

GET https://www.googleapis.com/gmail/v1/users/me/threads/14eaffaf5e3e8242?fields=messages%2Fid%2Cmessages%2Fpayload%2Fparts%2Fbody%2FattachmentId&key={YOUR_API_KEY}

Response:

{
 "messages": [
  {
   "id": "14eaffaf5e3e8242",
   "payload": {
    "parts": [
     {
      "body": {  // This message had an attachment.
       "attachmentId": "ANGjdJ_0lphTo48BO0xBT_YOSo3tYah23hzpjyATe3GwfziK0I6401P_8-ZYoGuCQPHhpPP0-S_pjL68WIEZzQ0tu72RcIOE4UY3kA4u8PjXPf3Cm5PxVJjmH9N0hm0fFX31RYo8bfZQ6l7bDbYbnCSZbckG7g8enGaKMPbBzIEEC4HXr_YghOYWSfrXKXiFLnxWN4LfsFk3IXUN2tVvMe_0xMhDDfBlqYPnXHr2PhPghq7bQojNxiH4YziIqaKmwiU4xqVfygbae-K-_Q2blyz0EgI4OXjMzwz56Q5e1w"
      }
     }
    ]
   }
  },
  {
   "id": "14eaffb277b61cd0" // This message had no attachment.
  }, ...
 ]
}

As you can see in the first request, no part of the body is retrieved when asking for specific metadata headers. Individual fields are also hard to pick out in the fields-parameter, since headers are not key-value pairs, but objects on the form { "name": <HEADER_NAME>, "value": <HEADER_VALUE> }.

Is there any way to combine these two requests? I would like to get all the relevant metadata about a message at the same time as getting how many attachments there are in the message.


Solution

  • From Users.threads.get.

    "metadata": Returns email headers with message metadata such as identifiers and labels.

    The fields parameter is only used to limit the amount of data returned. Since metadata mode is already a limited response you can't use fields to get data outside of that subset. Your best option would be to use your second example with fields and then filter the metadata values locally.