1

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.

0

1 Answer 1

0
  • 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)
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for sharing your answer.I have tried above script..am able to send email item successfully but without attachment.
@J P Thank you for replying. From your comment, it is found that my answer works. But about without attachment, I think that the reason is due to your above script, and your above script cannot create correctly the draft email. But in your script, payload_data is not clear. So at first, I supposed that You have already been able to create correctly a draft email.. If you want to modify your above script, please check my updated answer. I added a sample script for creating a draft email. If this is useful, I'm glad.
@J P Did my answer show you the result what you want? Would you please tell me about it? That is also useful for me to study. If this works, other people who have the same issue with you can also base your question as a question which can be solved. If you have issues for my answer yet, I apologize. At that time, can I ask you about your current situation? I would like to study to solve your issues.
I have changed my draft message with above changes and its working fine..thank you for your help..I had missed some formatting changes in my draft message
@J P Thank you for your response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.