4
votes

Is there a good way to embed a Google Document into an email?

I can start with:

var doc = DocumentApp.openById('1P_KZr_xpg.....xntBqvQ');

I've tried these approaches:

A) MailApp.sendEmail('[email protected]', doc.getName(), doc.getText()); The raw text from the document forms the body of the email... all formatting is lost.

B) MailApp.sendEmail('[email protected]', doc.getName(), doc.getUrl()); The URL to the document is the body of the message. The content of the document is not seen until you click through to the source document.

C) MailApp.sendEmail('[email protected]', doc.getName(), '', { htmlBody: HtmlService.createHtmlOutput(doc.getAs('blob') }); This seems promising, but gives an error: "Unsupported conversion requested."

Is there any other way to embed a document?

Is there any way to get the HTML version of a document? Once I have that, I can use htmlBody to insert it.

1

1 Answers

5
votes

This has already been answered a few times, here is the code originally suggested by Henrique Abreu (don't care about comments saying it doesn't work, it does !):

function emailDocTest() {
  var id = 'Doc-Very-Long-ID-Here';
  var url = 'https://docs.google.com/feeds/';
  var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id,
                              googleOAuth_('docs',url)).getContentText();
  var emailAdress = Session.getEffectiveUser().getEmail();
  MailApp.sendEmail(emailAdress, 'test doc send by mail as html', 'html only', {htmlBody:doc});
}

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

Please note that the googleOAuth_ function need a special authorization that can only be activated using the script editor to run the function (not from a UiApp or from a menu) and that this function doesn't appear in the 'run' list because of the underscore at the end of its name (this is how it is intended to work) so run it at least once from the script editor and remember that if/when you eventually share the app with someone else. See feature request 677 for details.