Search code examples
pythongmail-apigoogle-apis-explorer

How to Find the Attachment ID for Getting an Email Using the Gmail API?


I use Python to access Gmail via the Gmail-API. I want to make a simple call to download the attachment of an email and for this you have to pass three parameters: ID, message ID and UserID. I have the last two, but where do I find the first? The Doc says that it's the ID of the attachment so I tried the option "show original" in Gmail, but with no success. The API keeps returning the error message "invalid attachment token". Where do I find the attachment ID?

https://developers.google.com/gmail/api/v1/reference/users/messages/attachments/get


Solution

  • In order to retrieve the the ID of the attachments of a certain message, you would have to get the message resource via Users.messages.get, and from that response, retrieve the ID of the attachment.

    This ID can be found in the body property of the corresponding message part (you can use properties like filename to know which attachment corresponds to each ID), as shown in this sample:

    {
      "payload": {
        "parts": [
          {
            "filename": {attachment_filename},
            "body": {
              "attachmentId": {attachment_id}
              // other body properties
            },
            // other part properties
          },
          // other parts
        ],
        // other payload properties
      },
      // other message properties
    }
    

    Reference: