Skip to content

Instantly share code, notes, and snippets.

@SvenFlorian
Last active January 15, 2017 13:51
Show Gist options
  • Save SvenFlorian/8d28142eff7daaf671987ce57eeb9a45 to your computer and use it in GitHub Desktop.
Save SvenFlorian/8d28142eff7daaf671987ce57eeb9a45 to your computer and use it in GitHub Desktop.
Google Apps Script code that saves HTML formatted text as a gmail draft using UTF-8
/* CREDIT */
// Code base and instructions for how to set it up - Cyrus Loree: http://stackoverflow.com/questions/25391740/how-to-use-the-google-apps-script-code-for-creating-a-draft-email-from-985/25457193#25457193
// How to format raw email data - Tholle: http://stackoverflow.com/questions/24908700/mail-attachment-wrong-media-type-gmail-api/24957873#24957873
// Additional added functionality by me: UTF-8 encoding, so that it works for any kind of characters (eg Nordic å, ä, ö)
function createDraft(to, cc, sendAs, subject, htmlBody) {
try{
var forScope = GmailApp.getInboxUnreadCount(); // needed for auth scope
var raw =
'Subject: ' + subject + '\r\n' +
'To: ' + to + '\r\n' +
'Cc: ' + cc + '\r\n' +
'From: ' + sendAs + '\r\n' +
'Content-Type: multipart/alternative; boundary=1234567890123456789012345678\r\n' +
'--1234567890123456789012345678\r\n' +
'Content-Type: text/html; charset="UTF-8"\r\n' +
'MIME-Version: 1.0\r\n' +
'Content-Transfer-Encoding: 7bit\r\n\r\n' +
htmlBody + '\r\n' +
'--1234567890123456789012345678--\n';
var draftBody = Utilities.base64Encode(raw, Utilities.Charset.UTF_8);
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());
}catch(err){
Logger.log(err.lineNumber + ' - ' + err);
}
}
/* EXAMPLE HTML TEXT */
/**
<b># DL to reply:</b> 10th of September<br/><br/>
Hello, hello! :)<br/><br/>
This is an example HTML text. I can link to <a href='www.google.com'>google</a> and even include an image from the web! :D<br/><br/>
<img src='http://cdn.litlepups.net/2016/04/17/kitten-free-stock-photo-a-cute-orange-kitten-isolated-on-a-white.jpg'/><br/><br/>
Hugs,<br/>
Sender
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment