Google应用脚本 - 将文档附加/嵌入到电子邮件中

时间:2012-11-17 06:17:50

标签: google-apps-script

是否有将Google文档嵌入电子邮件的好方法?

我可以从:

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

我尝试过这些方法:

A)MailApp.sendEmail('john@abc.com', doc.getName(), doc.getText()); 文档中的原始文本构成了电子邮件的正文......所有格式都丢失了。

B)MailApp.sendEmail('john@abc.com', doc.getName(), doc.getUrl());文档的URL是邮件的正文。在您单击源文档之前,不会看到文档的内容。

C)MailApp.sendEmail('john@abc.com', doc.getName(), '', { htmlBody: HtmlService.createHtmlOutput(doc.getAs('blob') });这似乎很有希望,但是会出错:“请求的转换不受支持。”

还有其他方法可以嵌入文档吗?

有没有办法获取文档的HTML版本?一旦我有了,我可以使用htmlBody插入它。

1 个答案:

答案 0 :(得分:5)

这已经回答了几次,这里是Henrique Abreu的代码originally suggested(不关心评论说它不起作用,确实如此!):

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

请注意,googleOAuth_函数需要一个特殊授权,只能使用脚本编辑器激活该函数来运行该函数(不是来自UiApp或菜单),并且此函数不会出现在“运行”列表中因为它名称末尾的下划线(这就是它的工作方式)所以从脚本编辑器至少运行一次并记住,如果/当你最终与其他人共享应用程序时。有关详细信息,请参阅feature request 677