How to send rich text emails with GmailApp?

2019-03-03 08:27发布

I’m trying to send a Google Doc, with all of its formatting, in an email.

function sendGoogleDocInEmail() {

  var doc = DocumentApp.openById("example_Id");
  var body = doc.getBody();
  var text = body.getText();

  GmailApp.sendEmail("emailaddress@gmail.com", "Hi", text);

This code works fine, but the email is sent as plain text.

I have descriptive hyperlink text pieces in the Google Doc, and they lose their hyperlinks when converted to plain text.

Is there any way I can keep all of the hypertext formatting when sending the email?

I’ve tried passing the body object to the method instead, but that just sends an email with DocumentBodySection in the body.

Thanks!

1条回答
男人必须洒脱
2楼-- · 2019-03-03 09:01

Trying using a combination of this script: https://stackoverflow.com/a/28503601/3520117

And then using the htmlBody parameter of the MailApp.sendEmail method.

Untested, but should work:

function emailGoogleDoc(){
  var id = DocumentApp.getActiveDocument().getId() ;
  var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
  var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=html";
  var param = {
    method      : "get",
    headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    muteHttpExceptions:true,
  };
  var html = UrlFetchApp.fetch(url,param).getContentText();
  Logger.log(html);

  var email = person@domain.tld;  
  var subject = 'Subject line';
  var body = "To view this email, please enable html in your email client.";

  MailApp.sendEmail(
    email,           // recipient
    subject,         // subject 
    body, {          // body
      htmlBody: html // advanced options
    }
  );
}
查看更多
登录 后发表回答