3

Using the script below on a Google Doc, I'm trying to send the document as HTML in an email body. It's converting the document correctly (when I check the exported document via the url) and sending the email with the same content, but it loses the following formatting at some point: font format (e.g., size, color) and table format (e.g., borders, background color)

function sendGoogleDocAsHTML(){
  var id = DocumentApp.getActiveDocument().getId() ;
  var url = "https://docs.google.com/document/d/"+id+"/export?format=html"
  var param = {
method      : "get",
headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
  };
  var html = UrlFetchApp.fetch(url, param);
  var email = <EMAIL>;
  var subject = <SUBJECT>;
  GmailApp.sendEmail(email, subject,"", {htmlBody:html});
}

How do I preserve the format in the email?

Rubén
  • 34,714
  • 9
  • 70
  • 166
ken
  • 41
  • 1
  • 4
  • 1
    Does the original HTML include links to CSS files? I think that html in an email only supports inline styling. (inline CSS - inside a specific HTML element) – Alan Wells Mar 06 '17 at 14:13
  • And even inline styles won't be fully supported , Gmail interprets HTML and CSS very poorly – Juan Diego Antezana Mar 06 '17 at 14:50
  • The original HTML does not include links to CSS files. Looks like it uses internal CSS (I'm seeing a long – ken Mar 06 '17 at 15:05
  • 1
    You have to work on each item type. It has been a while since I tried to do this (ended up going in a different direction) so I have some old code but not sure it is actually working. I know I had to deal with various [element types](https://developers.google.com/apps-script/reference/document/element-type) individually, such as get a blob for an image. Everything I had was apparently from [this developers blog post](http://googleappsdeveloper.blogspot.com/2011/10/4-ways-to-do-mail-merge-using-google.html) – Karl_S Mar 06 '17 at 15:19

1 Answers1

6

This worked fine for me. Hope this may help

  function sendGoogleDocAsHTML(){
  var id = DocumentApp.getActiveDocument().getId() ;
  var url = "https://docs.google.com/document/d/"+id+"/export?format=html"
  var param = {
      method      : "get",
      headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions:true,
  };
  var html = UrlFetchApp.fetch(url, param);
  var raw = Utilities.base64EncodeWebSafe("Subject: Test\r\n" +
                                            "To: test@gmail.com\r\n" +
                                            "Content-Type: text/html; charset=UTF-8\r\n\r\n" +
                                            html+"\r\n\r\n");
   var message = Gmail.newMessage();
   message.raw = raw;
   var sentMsg = Gmail.Users.Messages.send(message, 'me');
}
Adharsha Neel
  • 452
  • 4
  • 16