Getting full HTML as a mail from google app scripts rather than the evaluated output

Viewed 34

I am trying to send an email to the person who fills my form. But I am getting the whole HTML code as the output rather than the evaluated version of it.

Any help??

code.gs

function doPost(e) {
   
  var sheet = SpreadsheetApp.getActiveSheet();
  var last=sheet.getLastRow();
  var dataRange = sheet.getRange(last, 1, 1, 4);
  var data = dataRange.getValues();
  for (var i in data) {
    var row = data[i];
    var emailAddress = row[2]; 
//    var email_address = Session.getActiveUser().getEmail();
    var htmlTemplate=HtmlService.createTemplateFromFile('email');
    htmlTemplate.name=row[1];
    var htmlBody= htmlTemplate.evaluate().getContent();
    var subject = 'Sending emails from a Spreadsheet';
    GmailApp.sendEmail(emailAddress, subject,  htmlBody);
    }
  }

email.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <p>from html <?= name ?></p>
  </body>
</html>

current output

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <p>from html Bob</p>
  </body>
</html>
1 Answers

Replace the following code with modification that shall work in your case, since you are trying to send an email, you should use createHtmlOutputFromFile, and to replace the content with dynamic value, replace function is easier to write, you may refer to my version on html template also

From:

var htmlTemplate=HtmlService.createTemplateFromFile('email');
    htmlTemplate.name=row[1];
    var htmlBody= htmlTemplate.evaluate().getContent();
    var subject = 'Sending emails from a Spreadsheet';
    GmailApp.sendEmail(emailAddress, subject,  htmlBody);
    }

To:

 var htmlTemplate=HtmlService.createHtmlOutputFromFile('email').getContent();
    htmlTemplate = htmlTemplate.replace('#NAME', row[1])
    var subject = 'Sending emails from a Spreadsheet';
    GmailApp.sendEmail(emailAddress, subject,'',{ htmlBody:htmlTemplate});
    }

Email template (body part), so that #Name will be replaced by sheet value:

<body>  
    <p>from html #NAME</p>
  </body>
Related