0
votes

Google documentation gave an example as below:

POST /upload/gmail/v1/users/userId/messages/send?uploadType=multipart HTTP/1.1 Host: www.googleapis.com Authorization: Bearer your_auth_token Content-Type: multipart/related; boundary=foo_bar_baz Content-Length: number_of_bytes_in_entire_request_body

--foo_bar_baz Content-Type: application/json; charset=UTF-8

{ "id": string, "threadId": string, "labelIds": [ string ], "snippet": string, "historyId": unsigned long, "payload": { "partId": string, "mimeType": string, "filename": string, "headers": [ { "name": string, "value": string } ], "body": users.messages.attachments Resource, "parts": [ (MessagePart) ] }, "sizeEstimate": integer, "raw": bytes }

--foo_bar_baz Content-Type: message/rfc822

Email Message data --foo_bar_baz-- If the request succeeds, the server returns the HTTP 200 OK status code along with any metadata:

HTTP/1.1 200 Content-Type: application/json

{ "id": string, "threadId": string, "labelIds": [ string ], "snippet": string, "historyId": unsigned long, "payload": { "partId": string, "mimeType": string, "filename": string, "headers": [ { "name": string, "value": string } ], "body": users.messages.attachments Resource, "parts": [ (MessagePart) ] }, "sizeEstimate": integer, "raw": bytes }

Can someone make a sample request body by looking at the above example? I need to send an email with attachment.

1

1 Answers

0
votes

Based from SO related post, the body request can be something like this:

var mail = [
  'Content-Type: multipart/mixed; boundary="foo_bar_baz"\r\n',
  'MIME-Version: 1.0\r\n',
  'From: [email protected]\r\n',
  'To: [email protected]\r\n',
  'Subject: Subject Text\r\n\r\n',

  '--foo_bar_baz\r\n',
  'Content-Type: text/plain; charset="UTF-8"\r\n',
  'MIME-Version: 1.0\r\n',
  'Content-Transfer-Encoding: 7bit\r\n\r\n',

  'The actual message text goes here\r\n\r\n',

  '--foo_bar_baz\r\n',
  'Content-Type: image/png\r\n',
  'MIME-Version: 1.0\r\n',
  'Content-Transfer-Encoding: base64\r\n',
  'Content-Disposition: attachment; filename="example.png"\r\n\r\n',

   pngData, '\r\n\r\n',

   '--foo_bar_baz--'
].join('');

    var response = UrlFetchApp.fetch(
        "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=media", {
            method: "POST",
            headers: {
                "Authorization": "Bearer " + ScriptApp.getOAuthToken(),
                "Content-Type": "message/rfc822",
            },
            muteHttpExceptions: true,
            payload: mail
});

Here's also an example code from digital inspiration written by Amit Agarwal in Google Appscript. This example shows how you can easily send email messages with file attachment using Gmail API.