I am just curious as to why/how this works.
I have a function called sendEmail that defines a bunch of variables from a spreadsheet then sends the user an email using said variables. However, I get the error that these variables are not defined unless I declare these variables OUTSIDE the function. Anyone know why this is? I just want to better understand how JavaScript works.
Example, the below doesn't work if there is a scriptlet for firstName in the HTML template, it only works when firstName is defined outside the function.
function sendEmail () {
const ss = SpreadsheetApp.getActive().getSheetByName('Employee Names');
const firstName = ss.getRange(7, 1).getValue();
var htmlBody = HtmlService.createTemplateFromFile("EmailTemplate2").evaluate().getContent();
MailApp.sendEmail(
{to: Session.getActiveUser().getEmail(),
subject: `Attendance Infractions Narrative`,
htmlBody: htmlBody});
}
Try this:
function sendEmail() {
const ss = SpreadsheetApp.getActive().getSheetByName('Employee Names');
let t = HtmlService.createTemplateFromFile("EmailTemplate2")
t.firstName = ss.getRange(7, 1).getValue(); //this will wori with <?= firstName ?>
MailApp.sendEmail(
{
to: Session.getActiveUser().getEmail(),
subject: `Attendance Infractions Narrative`,
htmlBody: t.evaluate().getContent();
});
}