Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Send HTML Email? #7

Closed
nelsonic opened this issue Oct 19, 2015 · 6 comments
Closed

Send HTML Email? #7

nelsonic opened this issue Oct 19, 2015 · 6 comments

Comments

@nelsonic
Copy link
Member

Can we send an HTML email?

@nelsonic
Copy link
Member Author

@grimmthetallest
Copy link

HTML format emails can be uploaded to the Gmail API using GAS. First the Advanced Google Services option for Gmail must be enabled and the Gmail API must also be enabled in the Developers Console.

Here's the code I'm currently using to do this, based heavily on oshliaer's solution here - https://gist.github.com/oshliaer/8db2131bf7357247bc2b

I'm brand new to JavaScript so you'll have to forgive me for any formatting errors.

function sendHTML(){
var forScope = GmailApp.getInboxUnreadCount(); //needed for authentication

//build, encode, upload draft

var someUser = 'recipient@person.com'

var r = new RAW_();
r.from = 'John Smith <' + 'johnsmith@person.com' + '>';
r.to = 'Some User <' + someUser + '>';
r.subject = 'New Email!';
r.body = '<html><body>' + 'You have a new email!' + '</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);
draftID = /: "(.*)"/.exec(resp.getContentText())[1];

//use draft ID to send newly created draft

var params =
    {
      method: "post", 
      contentType: "application/json", 
      headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}, 
      muteHttpExceptions: true, 
      payload: JSON.stringify({ "id": draftID }) 
    };

var resp = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/me/drafts/send", params);
Logger.log(resp.getResponseCode());
Logger.log(resp.getContentText());
}

//builds RFC spec headers

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

//uses regex to replace some problematic characters

RAW_.prototype.encode = function(){
  return Utilities.base64Encode(this.toRFC(), Utilities.Charset.UTF_8).replace(/\//g,'_').replace(/\+/g,'-');
}

@nelsonic
Copy link
Member Author

nelsonic commented Jan 5, 2016

Nice one @grimmthetallest 👍
Welcome to https://github.com/dwyl !
(you appear to be new to GitHub too... 😉)
Your code looks good. have you tried it?

@grimmthetallest
Copy link

Yes, I've been successfully using this code to email the content of a submitted Google Form to a manager selected in said form.

The first time this script is run in Google Apps Script (after the Advanced Google Services and API options for Gmail are turned on for the project) it will request authorization for mailbox access.

Haven't used much of the additional HTML capability myself aside from concatenating some variables into the string that makes up the body of the email, but so far it uploads and sends properly.

@mckennapsean
Copy link
Collaborator

mckennapsean commented Jan 18, 2017

A potential solution was shared in response to #41, which does require some customization of the Google Script but looks quite nice. It does not change the client-side Javascript, and an additional step would have to go into the tutorial to explain this otherwise folks can just find it by searching the issues here!

@mckennapsean
Copy link
Collaborator

mckennapsean commented Feb 12, 2017

@grimmthetallest - we just pulled in an HTML-formatted email solution that cleans up the displayed data in #74 (step 13)

The code for creating gmail drafts is very cool! Unfortunately, it seems a little complex (at least, forgive me, I don't get all the code!). If you think there is anything worth improving with our solution, please do let us know! :)

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

No branches or pull requests

3 participants