Google Apps脚本MailApp使用htmlBody文档

时间:2013-05-09 07:45:29

标签: google-apps-script

我有一个简单的文档/模板,我想在向用户发送电子邮件时使用。它适用于文本版本,但我无法弄清楚,如何以HTML格式发送文档。该文档仅包含带有粗体格式的文本。

function sendEmail(emailAddress, attachment){
    var EMAIL_TEMPLATE_ID = "SOME_GOOGLE_DOC_ID";
    var emailTemplate = DocumentApp.openById(EMAIL_TEMPLATE_ID);
    MailApp.sendEmail(emailAddress, "Subject", emailTemplate.getText(), {  
        htmlBody: emailTemplate, <-- THIS does not return correct data  });
}

3 个答案:

答案 0 :(得分:2)

我找到的答案就是这个

function getDocAsHtml(docId){ 
  var url = 'https://docs.google.com/feeds/download/documents/Export?exportFormat=html&format=html&id=';
  return UrlFetchApp.fetch(url+docId).getContentText();
}

效果很好

答案 1 :(得分:0)

htmlBody参数需要一个字符串,而emailTemplate变量的类型为Document。

您应该使用类似

的内容
 MailApp.sendEmail(emailAddress, "Subject", emailTemplate.getText(), {  
        htmlBody: emailTemplate.getBody().getText()  });

答案 2 :(得分:0)

如果我们利用Roman Vialard的DriveApp库,这是相当直截了当的。您需要按照here的说明将库添加到项目中,然后才能使用下面的代码。

/**
 * get a String containing the contents of the given document as HTML.
 * Uses DriveApp library, key Mi-n8njGmTTPutNPEIaArGOVJ5jnXUK_T.
 *
 * @param {String} docID ID of a Google Document
 *
 * @returns {String} Content of document, rendered in HTML.
 *
 * @see https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/driveservice
 */
function getDocAsHTML(docID) {
  var doc = DriveApp.getFileById(docID);
  var html = doc.file.content.src;
  var response = UrlFetchApp.fetch(html);
  var template = response.getContentText();

  return template;
}

function sendEmail(emailAddress, attachment){
    var EMAIL_TEMPLATE_ID = 'SOME_GOOGLE_DOC_ID';
    var emailTemplate = getDocAsHTML(EMAIL_TEMPLATE_ID);
    MailApp.sendEmail(emailAddress, "Subject", emailTemplate.getText(), {  
        htmlBody: emailTemplate });
}