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();
}
}
}
I just tried this code and it sent three emails and when I ran it again it sent none:
gs:
Sheet0 before running:
Sheet0 after running: