How to use html file as htmlBody?

Viewed 1709

How to use html file as htmlBody??

I know that I can use MailApp.sendEmail to sent an email. And I know I can set htmlBody with html code. However my html code are to long and have many lines,so I want to write them in a extra html file not just using one gs file with so many "+". How can I do that?

2 Answers

How about this sample script? Please think of this as one of several answers.

When you put HTML body to your script editor as a HTML file, you can achieve it by using HtmlService.createHtmlOutputFromFile(). The sample script is as follows.

Sample script :

var blob = HtmlService.createHtmlOutputFromFile("### HTML filename without extension ###").getBlob();
MailApp.sendEmail({
  to: "### Your e-mail address ###",
  subject: "sample subject",
  htmlBody: blob.getDataAsString()
});

References :

If I misunderstand your question, I'm sorry.

Edit :

If when you run the script, you want to update a table, you can use this sample script.

GAS :

var t = HtmlService.createHtmlOutputFromFile("### HTML filename without extension ###");
t.data = ["sample1", "sample3", "sample3"];
var blob = t.evaluate().getBlob();
MailApp.sendEmail({
  to: "### Your e-mail address ###",
  subject: "sample subject",
  htmlBody: blob.getDataAsString()
});

HTML :

<table>
  <? for (var i = 0; i < data.length; i++) { ?>
    <tr>
        <td><?= data[i] ?></td>
    </tr>
  <? } ?>
</table>

References :

Sometimes I like to build these files in Ultraedit and store them on the google drive as a txt files and I extract them html as string as follows.

MailApp.sendEmail({
  to: emailaddress,
  subject: subject,
  htmlBody: loadMyFile(filename,folderID)}
);

function loadMyFile(filename,folderID){
  var fldr=DriveApp.getFolderById(folderID);
  var file=fldr.getFilesByName(filename);
  while(file.hasNext()){
    var fi=file.next();
    var target=fi.getName();
    if(target==filename){
      var s=fi.getBlob().getDataAsString();
    }
  }
  return s;
}
Related