2
votes

I cannot seem to successfully get an html string to show up inside a template. All non-html string values seem to evaluate and show up in the email correctly. I've looked through the documentation / Stack Overflow and can't seem to find anything on this specifically.

Apps Script Code:

function sendReceiptEmail(order_id, data){
  const exceptions = ["name", "address", "email", "total", "building_code", "status"];

  var items = '';
  for (item in data) {
    if (exceptions.indexOf(item) == -1){
      items += "<tr><td>" + item + "</td><td>" + data[item] + "</td></tr>"
    }
  }
  var htmlBody = HtmlService.createTemplateFromFile('customer-email');

  htmlBody.name = data.name;
  htmlBody.order_id = order_id;
  htmlBody.address = data.address;
  htmlBody.email = data.email;
  htmlBody.total = data.total;
  htmlBody.building_code = data.building_code;
  htmlBody.timestamp = getFormattedDate(new Date());
  htmlBody.items = items;

  var message = htmlBody.evaluate().getContent();
  var subject = "Order #" + order_id;

  MailApp.sendEmail({
    to: data.email,
    subject: subject,
    htmlBody: message
  });
};

HTML Template

<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h2>Thanks for your order, <?= name ?></h2>
    <p>Please see your order details below.</p>

    <p><strong>Name: </strong><?= name ?></p>
    <p><strong>Email: </strong><?= email ?></p>
    <p><strong>Address: </strong><?= address ?></p>
    <p><strong>Building Code: </strong><?= building_code ?></p>
    <p><strong>Date: </strong><?= timestamp ?></p>
    <br/>
    <p><strong>Subtotal: </strong>$ <?= total ?></p>
    <p><strong>Delivery Fee: </strong>$ 5.00</p>
    <p><strong>Total: </strong>$ 5.00</p>

    <h3><strong>Order Summary</strong></h3>
    <table>
      <tr>
        <th>Item</th>
        <th>Quantity</th>
      </tr>
      <?= items ?>
    </table>

  </body>
</html>

Result: enter image description here

1

1 Answers

2
votes

How about this modification? I think that the reason of your issue is due to <?= of <?= items ?>. The official document says as follows.

Printing scriptlets, which use the syntax , output the results of their code into the page using contextual escaping.

In this case, please modify it to <?!=. The official document says as follows.

Force-printing scriptlets, which use the syntax <?!= ... ?>, are like printing scriptlets except that they avoid contextual escaping.

From:

<?= items ?>

To:

<?!= items ?>

Reference: