Home > database >  Google Script - Send email for last row when insert a new value
Google Script - Send email for last row when insert a new value

Time:06-10

I'm new in Google Script, I'm trying to send an email when a new row is created, and only the last email (row) will receive the email. My code is below:

  var spreadSheet = SpreadsheetApp.getActiveSheet();
  var dataRange = spreadSheet.getDataRange();

  // Fetch values for each row in the Range.
  var data = dataRange.getValues();



  var text = 'You have successfully registered for the Teams Training on June 16th at 12:00 pm. Lunch will be provided.';
  for (var i = 1; i < data.length; i  ) {
    (function(val) {
      var row = data[i];
      var name = row[0]; // position of name header — 1
      var lname = row[1]; // position of name header — 1
      var emailAddress = row[3]; //position of email header — 1
      var seat = row[4]; // position of name header — 1
      var message = 'Dear '   name   ' '  lname   '\n\n'   text   '\n\nYOUR SEAT NUMBER: '   seat;
      var subject = 'Teams training registration';
      MailApp.sendEmail(emailAddress, subject, message);
      })
      (i);
   }
} 

Right now is sending all the rows and it's not automatic when a row is created. If you can help would be awesome! Thank you

CodePudding user response:

Using onEdit to send email

  • Enter sheet name where requested

  • create an installable onEdit and name in onMyEdit

  • use e in the function declaration to hold the event object.

  • Also please add a column of check boxes at column 6

When the checkboxes are clicked to true the email will be sent for that row

function onMyEdit(e) {
  e.source.toast("Entry");
  const sh = e.range.getSheet();
  if (sh.getName() == "Enter your sheet new" && e.range.columnStart == 6 && e.value == "TRUE") {
    e.source.toast("Flag1")
    var text = 'You have successfully registered for the Teams Training on June 16th at 12:00 pm. Lunch will be provided.';
    const vs = sh.getRange(e.range.rowStart,1,1,sh.getLastColumn()).getValues().flat();
    var name = vs[0]; 
    var lname = vs[1]; 
    var emailAddress = vs[3]; 
    var seat = vs[4]; 
    var message = 'Dear '   name   ' '   lname   '\n\n'   text   '\n\nYOUR SEAT NUMBER: '   seat;
    var subject = 'Teams training registration';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}
  • Related