Search code examples
google-apps-scriptgoogle-sheetshtml-emailtemplate-engine

How come my forEach loop gets error when sending emails


I am sure the answer is staring at me right in the face but I'm a bit confused. I have a spreadsheet with employee information and I created a forEach loop (below) so that at the end of each row it should send an email with information from the row. However, the HTML file is not recognizing value[0], value[1], etc and I am getting the following error message: ReferenceError: value is not defined

function ncnsEmailFunction () {

const values = ncnsSheet.getRange(2, 1, 10, 6).getValues();

values.forEach(function(value, index){
if (value[0] === "") return;

const htmlBody = HtmlService.createTemplateFromFile("NCNSEmailTemplate").evaluate().getContent();
MailApp.sendEmail({
  to: Session.getActiveUser().getEmail(),
  subject: `NCNSEmailTemplate`,
  htmlBody: htmlBody,
  });

})

}

Here is what my HTML file looks like:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>

Hello <?=value[0]?>

  </body>
</html>

What can I do to fix this?


Solution

  • Try this:

    function ncnsEmailFunction() {
      const ss = SpreadsheetApp.getActive();
      const ncnsSheet = ss.getSheetByName("Your sheet name")
      const values = ncnsSheet.getRange(2, 1, 10, 6).getValues();
      values.forEach(function (value, index) {
        if (value[0] === "") return;
        let t = HtmlService.createTemplateFromFile("NCNSEmailTemplate");
        t.value = value[0];
        const htmlBody = t.evaluate().getContent();
        MailApp.sendEmail({to: Session.getActiveUser().getEmail(),subject: `NCNSEmailTemplate`,htmlBody: htmlBody});
      })
    }
    
    <!DOCTYPE html>
    <html>
      <head>
        <base target="_top">
      </head>
      <body>
    Hello <?=value?>
      </body>
    </html>