Skip to content

Instantly share code, notes, and snippets.

@catupper
Created November 9, 2016 11:15
Show Gist options
  • Save catupper/07bf1f6663f20c3b9e1f337095f54dff to your computer and use it in GitHub Desktop.
Save catupper/07bf1f6663f20c3b9e1f337095f54dff to your computer and use it in GitHub Desktop.
function createHTMLDraftInGmail(to, title, contents) {
var forScope = GmailApp.getInboxUnreadCount(); // needed for auth scope
var htmlBody = "<p>Hello, I am an HTML message</p><hr>";
var mail = [
"To: $to",
"Subject: =?utf-8?B?$subject?=",
"MIME-Version: 1.0",
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: 7bit",
"",
"$body"
].join("\n").trim();
mail = mail
.replace("$to", to)
.replace("$subject", Utilities.base64Encode(title.getContentText("shift-jis")))
.replace("$body", contents);
var encoded = Utilities.base64Encode(unescape(encodeURIComponent(mail)))
.replace(/\+/g, '-').replace(/\//g, '_');
var params = {
method : "post",
contentType : "application/json",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
payload:JSON.stringify({
"message": {
"raw": encoded
}
})
};
var resp = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/me/drafts", params);
Logger.log(resp.getContentText());
}
function fromISOJP(str){
var blob = Utilities.newBlob("");
blob.setDataFromString(str, "JIS");
return blob.getDataAsString();
}
function createDraft(to, subject, body) {
Logger.log(to);
var forScope = GmailApp.getInboxUnreadCount(); // needed for auth scope
subject = "=?ISO-2022-JP?B?" + Utilities.base64Encode(fromISOJP(subject))+ "?=";
body = fromISOJP(body);
var raw =
'Subject:' + subject + '\n' +
'To: ' + to + '\n' +
'MIME-Version: 1.0\n' +
'Content-Type: text/plain; charset=ISO-2022-JP; format=flowed; delsp=yes \n' +
'Content-Transfer-Encodeing: 7bit\n\n'+
body + '\n'
var draftBody = Utilities.base64EncodeWebSafe(raw);
var params = {method:"post",
contentType: "application/json",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
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.getContentText());
/*
* sample resp: {
* "id": "r3322255254535847929",
* "message": {
* "id": "146d6ec68eb36de8",
* "threadId": "146d6ec68eb36de8",
* "labelIds": [ "DRAFT" ]
* }
* }
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment