Email From a Google Sheet: Claim the Row Before You Send It
Every guide to sending email from a Google Sheet ends with the same safety rule: write SENT next to each row after you mail it, so a rerun skips what already went out. The rule is right, and on its own it does not stop a double send. It stops the next run from repeating the last one. It does nothing about two runs that are reading the sheet at the same time. That happens more easily than it…
When sending email through a Google Sheet, a crucial safety tip is to mark each row as SENT after it has been mailed. This prevents duplicate emails from being sent if the process is rerun. However, this single step is not enough to completely prevent double sends. Concurrent runs of the function that installs the automated email trigger can cause issues.
If the function is executed twice at the same time, both will attempt to read the sheet before the first run has marked the row as SENT. This results in the same recipients receiving the email twice, and the sheet remains clean.
To address this problem, an additional layer of protection is needed. The recommended solution involves creating a state system for each row, where it must change its status to claim it before actually sending the email. There are four possible statuses: blank (not sent yet), SENDING (claimed, outcome not recorded), SENT the sender accepted it, and FAILED: reason the sender rejected it.
When a row moves to the SENDING status, a script lock is employed to prevent other runs from accessing the sheet simultaneously. After setting the status to SENDING, the SpreadsheetApp.flush() method is called to ensure that the change is written to the sheet immediately, rather than being stored in pending writes. This process helps ensure that only one run will successfully send the email, while the others either skip or record a failed attempt.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to