Search code examples
google-apps-scriptgmail

How to use html file as htmlBody?


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?


Solution

  • 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 :