Search code examples
google-apps-scriptgmail-apigoogle-app-makergoogle-apis-explorer

send email with attachment in appscript using media upload method


I have created a draft message using "media upload" method using below code

var draftUploadUrl = "https://www.googleapis.com/upload/gmail/v1/users/me/drafts?uploadType=media";

var response = UrlFetchApp.fetch(draftUploadUrl, {
  method: "POST",
  headers: {
    //authorizing request through service account
    "Authorization": "Bearer " + service.getAccessToken(),
    "Content-Type": "message/rfc822",
  },

  muteHttpExceptions: true,

  //payload_data is mime content with base64 encode of email body an 
  //attachment 
  payload: payload_data
});


draftID = /: "(.*)"/.exec(response.getContentText())[1];

console.log("draftID: " + draftID);

I get a draft ID of the message, how can I set draft ID in parameters to send the email with an attachment?

code snippets

var resp1 = UrlFetchApp.fetch("https://www.googleapis.com/upload/gmail/v1/users/me/drafts/send?uploadType=media", {
  method: "POST",
  headers: {
    "Authorization": "Bearer " + service.getAccessToken(),
    "Content-Type": "message/rfc822"
  },
  muteHttpExceptions: true,
  payload: JSON.stringify({
    "id": draftID
  })
});

it is throwing error "Invalid draft".Can you please guide how to pass ID parameter for above url call or what went wrong in above code?

Thanks in advance.


Solution

    • You have already been able to create correctly a draft email.
    • You want to send the created draft mail by directly requesting to the endpoint of Gmail API using Google Apps Script.

    If my understanding is correct, how about this modification?

    Modification points:

    • Use https://www.googleapis.com/gmail/v1/users/me/drafts/send as the endpoint.
    • Use application/json as Content-Type.

    Modified script:

    var resp1 = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/me/drafts/send", {
      method: "POST",
      headers: {
        "Authorization": "Bearer " + service.getAccessToken(),
        "Content-Type": "application/json"
      },
      muteHttpExceptions: true,
      payload: JSON.stringify({
        "id": draftID
      })
    });
    

    Note:

    • This modification supposes that you have already been able to use Gmail API using the access token.
    • If the format of draft mail is not complete, when the draft mail is sent, there is the case that an error occurs.

    Reference:

    If I misunderstand your question, I apologize.

    Edit:

    When you want to create a draft email including an attachment file, how about this sample script? This is from https://stackoverflow.com/a/45992149/7108653.

    Sample script:

    This sample script creates a draft email using Gmail API.

    function createDraft() {
      var fileId = "### file id ###"; // Please set this.
      var file = DriveApp.getFileById(fileId);
      var forScope = GmailApp.getInboxUnreadCount();
      var htmlBody = 'sample HTML body'; // Please set this.
      var raw = 
          'Subject: sample subject\r\n' + // Please set this.
          'To: [email protected]\r\n' + // Please set this.
          'Content-Type: multipart/mixed; boundary=##########\r\n\r\n' +
          '--##########\r\n' +
          'Content-Type: text/html; charset=UTF-8\r\n\r\n' + htmlBody + '\r\n' +
          '--##########\r\n' +
          'Content-Type: ' + file.getMimeType() + '; charset=UTF-8; name="' + file.getName() + '"\r\n' +
          'Content-Disposition: attachment; filename="' + file.getName() + '"\r\n' +
          'Content-Transfer-Encoding: base64\r\n\r\n' + Utilities.base64Encode(file.getBlob().getBytes()) +
          '\r\n--##########\r\n';
      var draftBody = Utilities.base64EncodeWebSafe(raw, Utilities.Charset.UTF_8);
      var params = {
        method:"post",
        contentType: "application/json",
        headers: {"Authorization": "Bearer " + service.getAccessToken()},
        muteHttpExceptions: true,
        payload: JSON.stringify({"message": {"raw": draftBody}})
      };
      var resp = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/me/drafts", params);
      Logger.log(resp)
    }