Skip to content

Instantly share code, notes, and snippets.

@oshliaer
Last active October 7, 2018 07:25
Show Gist options
  • Save oshliaer/8db2131bf7357247bc2b to your computer and use it in GitHub Desktop.
Save oshliaer/8db2131bf7357247bc2b to your computer and use it in GitHub Desktop.
Create a Gmail draft via Google Apps Script #gas #gmail
var RAW_ = function(){
//this['prOrder_'] = ['from', 'to', 'subject', 'MIME-Version', 'Content-Transfer-Encoding', 'Content-Type'];
this['prOrder_'] = ['from', 'to', 'subject', 'MIME-Version', 'Content-Type'];
this['from'] = ' ';
this['to'] = ' ';
this['subject'] = ' ';
this['MIME-Version'] = '1.0';
this['Content-Transfer-Encoding'] = 'BASE64';
this['Content-Type'] = 'text/html; charset=UTF-8';
this['body'] = ' ';
}
RAW_.prototype.toRFC = function(){
var line = '';
for(var i = 0; i < this.prOrder_.length; i++){
line += this.prOrder_[i] + ': ' + this[this.prOrder_[i]] + '\r\n';
}
line += '\r\n' + this['body'];
return line;
}
RAW_.prototype.encode = function(){
return Utilities.base64Encode(this.toRFC(), Utilities.Charset.UTF_8).replace(/\//g,'_').replace(/\+/g,'-');
}
function createDraftHTMLEmail(){
var forScope = GmailApp.getInboxUnreadCount();
var r = new RAW_();
r.from = 'Me <' + 'test@test.test' + '>';
r.to = 'You <'+ 'test@test.test' +'>';
r.subject = 'testing createDraftHTMLEmail';
r.body = '<html><body>' + '<h1>World</h1>Проверка <a href="http://google.com" target="_blank"> LINK </a>' + '</body></html>';
var draftBody = r.encode();
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);
}
@MrGreggles
Copy link

Oshliaer, I can't thank you enough for this. I've been inserting links manually for months into otherwise automated draft emails because I couldn't find a way to make links work. Bulk happiness karma to you and your family, seriously - you've made a stranger in a far away land very happy indeed! The world needs more dedicated and thoughtful people like you. Are you on oDesk by any chance? We may have automation work to outsource. Kudos ~

@oshliaer
Copy link
Author

Hi, MrGreggles.

Please, let me know if you need help. I have a little free time.

Cheers!

@MrGreggles
Copy link

Hi Alexander,

This is great and I'm using it every day now! Maybe the last issue is getting an attachment to work. I can do it via GmailApp.sendEmail() but I'm not technically savvy enough to work out how to do it in your draft code. I've tried putting the 'attachments' line in a few different places but with no success. I'm playing a guessing game. Is it possible? Thanks for any assitance. ~

// test - draft created but no attachment
var invoice = DocumentApp.openById('1uE5uR6LCYCdMv1YM0FvNgpG_F66kPVqDqPT6WD2BM4E');

var params = {
method: 'post',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
},
muteHttpExceptions:true,
payload:JSON.stringify({
'message': {
'raw': draftBody,
'attachments': [invoice.getAs(MimeType.PDF)]
}
})
};

var resp = UrlFetchApp.fetch('https://www.googleapis.com/gmail/v1/users/me/drafts', params);

@oshliaer
Copy link
Author

Hi MrGreggles
There is a example of drafts Create a Gmail draft with attachments via Google Apps Script

@Gsuz
Copy link

Gsuz commented Jul 16, 2015

Hi, would it be possible to add the user's gmail signature into this draft?

@brianncunningham
Copy link

So, I'm trying to modify your code to pull the contents of a google document, and make that the text of a draft gmail message. Things work OK, but all of the end of line feeds and blank line feeds have been stripped from the message. How could this be modified to work?

function createHTMLDraftInGmail() {

  var forScope = GmailApp.getInboxUnreadCount(); // needed for auth scope
//  var htmlBody = "<p>Hello, I am an HTML message</p><hr>";

  var doc = DocumentApp.openById('1fsRMxtLx3IBEYvmVy9W8uHLw3Uf2OIh4L7ZSxpkixbY');

  var body = doc.getBody();

  var mbody = body.getText();  

  var raw = 'Subject: Save Draft Message\r\n' +
            'Content-Type: text/html; charset=UTF-8\r\n' + 
            '\r\n' + mbody;

  var draftBody = Utilities.base64Encode(raw, Utilities.Charset.UTF_8).replace(/\//g,'_').replace(/\+/g,'-');

  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());
}

I appreciate your help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment