Question

I need to send a Google Document content as HTML by Gmail, showing the content in the message exactly as it looks in the document (see sample code below)

The HTML content the email recipients are receiving is not accurate, to say the least

  • If using Gmail to read the message, all the format is missing (image wrapping, font bold and colors)
  • If using Mozilla Thunderbird or Microsoft Outlook only the image wrapping is missing, but there is some extra top margin

Is there any way of doing this right or at least better??

Here the code I am using

function doc2mailtest() {
  var docId = "1glvAaYuYm25oZZVmHLaEySlPP-9fIqGwm17wAs1HpHc";
  // link to document: https://docs.google.com/a/thexs.ca/document/d/1glvAaYuYm25oZZVmHLaEySlPP-9fIqGwm17wAs1HpHc/edit
  var html = getDocAsHtml(docId); // OK but not accurate - ignore text format and image wrapping
  GmailApp.sendEmail("me@some.com", "Just testing MMD", '', { htmlBody: html });
  return;
}
function getDocAsHtml(docId) {
  var scope = 'https://docs.google.com/feeds/';
  var url = scope+'download/documents/Export?exportFormat=html&format=html&id=';
  var auth = googleOAuth_('docs',scope);
  return UrlFetchApp.fetch(url+docId,auth).getContentText();
}
function googleOAuth_(name,scope) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey('anonymous');
  oAuthConfig.setConsumerSecret('anonymous');
  return {oAuthServiceName:name, oAuthUseToken:"always"};
}

Thanks and regards, Fausto

Was it helpful?

Solution

There is an add-on for Google Docs to send an HTML email version of a document - open "Add-ons > Get Add-ons" and search for "email html".

For a coder's approach, Omar AL Zabir (user @oazabir) has written a good blog entry that walks through it: Google Docs to Clean HTML. Rather than relying on fetching the document as HTML, you traverse the document object to collect each element and build the HTML output.

Ensuring that the email looks just as the source document in all email clients is a big topic - too much for this forum. However, here are some points to keep in mind:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top