Receiving duplicate emails with sendEmail() from sheets

38 Views Asked by At

I have a script running so that when a particular cell is updated in a gSheet, it sends an email so that it can be actioned. The script itself works as expected, however, when a new email is sent, it gets sent multiple times (usually 2 or 3 times), and I can't figure out how to prevent this happening. There is only 1 onEdit trigger in place, and I have EMAIL_SENT included to prevent duplicates.

See script below:

var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 4;  // First row of data to process
var numRows = 1000;   // Number of rows to process
// Fetch the range of cells A2:H1000
var dataRange = sheet.getRange(startRow, 1, numRows, 100)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[5];
var message = "Message text";
var emailSent = row[6];
if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
  var subject = "Subject";
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 7).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
1

There are 1 best solutions below

2
Cooper On

I just tried this code and it sent three emails and when I ran it again it sent none:

gs:

function sendEmails2() {
  const sh = SpreadsheetApp.getActiveSheet();
  const sr = 4;
  var vs = sh.getRange(sr, 1, sh.getLastRow() - sr + 1,sh.getLastColumn() ).getValues();
  for (var i = 0; i < vs.length; i++) {
    var row = vs[i];
    var emailSent = row[6];
    if (emailSent != "EMAIL_SENT") { 
      MailApp.sendEmail(row[5], "Subject", "Message text");
      sh.getRange(i + 4, 7).setValue("EMAIL_SENT");
      SpreadsheetApp.flush();
    }
  }
}

Sheet0 before running:

COL1 COL2 COL3 COL4 COL5 COL6 COL7
1 2 3 4 5 Redacted
2 3 4 5 6 Redacted
3 4 5 6 7 Redacted

Sheet0 after running:

COL1 COL2 COL3 COL4 COL5 COL6 COL7
1 2 3 4 5 Redacted EMAIL_SENT
2 3 4 5 6 Redacted EMAIL_SENT
3 4 5 6 7 Redacted EMAIL_SENT