Home > Back-end >  Using Line Breaks in Google Apps Script HTML Variables
Using Line Breaks in Google Apps Script HTML Variables

Time:01-04

I'm trying to send an e-mail from Google Apps Script that uses variables. I have a template HTML set up with a "Header" and a "Message" variable. Whenever I pass html code to the "message" variable, it doesn't render as HTML but instead renders literally. I'd love to know how to get this working.

Thanks a ton.

code.gs

function sendEmail() {
var fileNo = '12345';
HtmlService.createTemplateFromFile('emailTemplate');
emailHTML.header = "New File Opened";
emailHTML.message =
    'A new file has been opened. <br> File Information: <br>'  
    'File Number: '   fileNo   '<br>';
MailApp.sendEmail([email protected], 'New File', "No HTML Client", {htmlBody: emailHTML.evaluate().getContent()});
};

emailTemplate.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <div style="text-align:center; font-family:Cambria;">
      <h2> <?= header ?> </h2>
      </div>
    <div style="background:#ececec; font-size:130%; color:black; margin-right:auto; margin-left:auto; padding:10px;">
      <?= message ?> <br> <br>
    </div>
  </body> 
</html>

Output Body:

"A new file has been opened. <br> File Information: <br>File Number: 12345<br>"

CodePudding user response:

You are using a printing scriptlet. From the documentation:

Printing scriptlets, which use the syntax <?= ... ?>, output the results of their code into the page using contextual escaping. Contextual escaping means that Apps Script keeps track of the output’s context on the page — inside an HTML attribute, inside a client-side script tag, or anywhere else — and automatically adds escape characters to protect against cross-site scripting (XSS) attacks.

To make it work, use a force-printing scriptlet <?!= ... ?>.

As a side note, the email address should in quotes:

  MailApp.sendEmail('[email protected]', 'New File', 'No HTML Client', { htmlBody: emailHTML.evaluate().getContent() });
  • Related