When calling the Gmail API in JavaScript to send a message with an HTML body and a ~100KB PDF attachment, the attachment correctly appears attached to the message in the sender's Gmail Sent folder, but does not appear on the message for the recipient.
The API call is a POST request to:
https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media
The request sent to the API is similar to this:
{
"headers": {
"Authorization": "Bearer {auth_token}"
},
"method": "POST",
"contentType": "message/rfc822",
"contentLength": 134044,
"payload": "{see_below}",
}
The request body is:
MIME-Version: 1.0
To: =?utf-8?B?TWlrZSBD?=<recipient@test.com>
CC: =?utf-8?B?TWlrZSBD?=<secondrecipient@gmail.com>
BCC: =?utf-8?B??=<bccrecipient@test.com>
From: =?utf-8?B?TWlrZSBxWXsd2lr?=<sender@test.com>
Subject: =?utf-8?B?subjectLine-removedForThisPost?=
Content-Type: multipart/alternative; boundary=__boundary__
--__boundary__
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: base64
{base64_encoded_string}
--__boundary__
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: base64
{base64_encoded_string}
--__boundary__
Content-Type: application/pdf; name="File Name.pdf"
Content-Disposition: attachment; filename="File Name.pdf"
Content-Transfer-Encoding: base64
{base64_encoded_string}
--__boundary__--
Note: The Gmail API Uploading Attachments documentation states that Content-Length is required when uploading a "simple" attachment (under 5MB). I made it so that my request includes Content-Length with an integer value of the total number of bytes of the PDF attachment. However, I noticed that Content-Length is not included in the payload.
I tried changing the Content-Type for the message from multipart/alternative to multipart/mixed - this made it so that the PDF attachment IS correctly attached to the recipient's message, but the HTML body of the message is rendered as plain text (the HTML tags are shown) and there is an additional attachment called noname.html which includes the HTML content rendered as HTML.
I need to make it so that the email in the recipient's message has both an HTML-rendered body AND the PDF attachment.
Update: I've uploaded examples of the raw email messages here. The sent message is on the left, and the received message is on the right.