The original guide on automatic payment reminders in Google Sheets gives you a 75-line Apps Script that checks a Receivables tab every morning, sends polite emails at 3, 7 and 14 days overdue, and logs the stage in column I.
On clean test rows it works as written. Before relying on it with real clients, I ran the exact script from the post against mocked Apps Script services using seven invented invoices that look like a real small-business sheet after a month of human edits: a pasted currency string, a credit note, a human note in the log column, a text due date, an Outlook semicolon email list, a clean overdue invoice sitting below it, and an accidental space in the paid column.
Out of seven rows, the script sent a client an email reading USD NaN, chased another client for USD -250.00, re-sent a stage-3 reminder that had already gone out, silently ignored a 19-day-overdue invoice, and crashed on row 6 before ever reaching the clean overdue invoice on row 7.
| Row (invented invoices, mocked Apps Script) | Original 75-line script | With the three blocks |
|---|---|---|
Row 2: Amount pasted as text "$1,250.00"
|
Emailed client USD NaN
|
Flagged BAD_AMOUNT in owner report |
Row 3: Credit note -250
|
Chased client for USD -250.00
|
Flagged NON_POSITIVE_AMOUNT
|
Row 4: Last reminder says "3 days"
|
Reset to 0, re-sent stage 3 |
Flagged BAD_LOG, did not resend |
Row 5: Due date pasted as text "2026-11-01"
|
Silently skipped at 19 days late | Flagged BAD_DATE in owner report |
Row 6: Email "ap@pine.test; cfo@pine.test"
|
Threw exception, aborted loop | Flagged BAD_EMAIL, loop continued |
Row 7: Clean overdue invoice (USD 640.00, 16 days) |
Never reached (0 emails) | Sent stage 14 reminder, logged 14
|
Row 8: Clean overdue invoice (USD 1500.00, " " in Paid) |
Silently treated as paid | Sent stage 7 reminder, logged 7
|
You do not need a billing SaaS to fix those five failure modes. Three short Apps Script blocks keep the same spreadsheet layout, add one optional Hold column (column J), validate every field before touching GmailApp, claim each row with a flushed timestamp before sending, and email you one daily summary whenever a row needs human cleanup.
Why the original script fails on real rows
Every failure above came from a specific line in the 75-line script, not from an exotic edge case.
-
String amounts turn into
USD NaN.buildMessage_formats the figure withNumber(d.amount).toFixed(2). When someone pastes"$1,250.00"or"1,250.00"into column D as text,getValues()returns a string,Number("$1,250.00")returnsNaN, andGmailApp.sendEmailhappily delivers"invoice INV-101 for USD NaN"to your customer. We hit a relatedgetValues()string trap in an earlier post on text amounts breaking commission totals. Here the cost is not an internal sum; it is an embarrassing email in a client's inbox. -
Credit notes and zero rows get chased. The original loop checks
!invoice,!email,paid, and!(due instanceof Date), but never checksamount. A negative credit note (-250) or a blank amount ("") passes every guard and asks the client to payUSD -250.00orUSD 0.00. -
Human notes in column I reset the log to zero. Column I holds
3,7, or14, and the script checksstage <= (Number(lastSent) || 0). If someone types"3 days"or"sent 3"in that cell,Number("3 days")evaluates toNaN, the|| 0turns it into0, and the client receives the stage-3 reminder again. -
One bad email aborts the entire morning run. There is no
try/catcharoundGmailApp.sendEmail. When a row contains"ap@pine.test; cfo@pine.test"(copied straight out of Outlook) or a typo with no domain,GmailApp.sendEmailthrows and kills the loop. Every valid overdue invoice below that row gets skipped until someone checks execution logs. -
Silent skips and accidental spaces hide unpaid invoices. A due date pasted as text (
"2026-11-01") failsdue instanceof Dateand hitscontinuewith no warning. A stray space" "in column F (Paid date) is truthy in JavaScript, soif (paid) continuetreats an unpaid invoice as paid forever. -
No lock and no claim-before-send. If a daily trigger overlaps with a manual run, or if two teammates both ran
installDailyTrigger(), both runs readlastSent = ""and send duplicate reminders. We covered the core claim-and-flush pattern in claiming a sheet row before sending email; here we pair it with a timestampedSENDING:state that never auto-unlocks.
The row decision path
Every unpaid row goes through four explicit gates before GmailApp.sendEmail is ever called. Nothing fails silently: if a row is overdue and unreadable, it goes into the owner summary instead of getting guessed or ignored.
Two design choices matter here:
-
Do not guess text amounts. It is tempting to strip
$and commas with a regex. That breaks the day a European client invoice arrives as"1.250,00": stripping commas turns it into1.25. Rejecting non-numeric amounts and emailing the owner the row number takes ten seconds to fix and never invents a number. -
Never auto-clear
SENDING:orFAILED:. If Apps Script dies mid-send (a 6-minute timeout or transient Gmail error), the script cannot know whether Gmail queued the email before the crash. LeavingSENDING:<stage>:<timestamp>orFAILED:<stage>:<timestamp>in column I and reporting it to the owner prevents silent double-sends. You check Sent Mail, either enter the stage number or clear the cell, and the next morning picks up cleanly.
Block 1: pure row validation and stage rules
Keep every decision in pure functions that take a row array and return a plain decision object (IGNORE, HOLD, FLAG, or SEND). None of these touch GmailApp or write to the sheet, which makes every edge case testable in plain Node.
The layout stays identical to the original guide, with one optional column J (Hold) for disputed invoices where ticking a checkbox or writing a note pauses reminders without pretending the invoice is paid.
const SHEET_NAME = 'Receivables';
const STAGES = [14, 7, 3]; // checked highest first
const BUSINESS_NAME = 'Your Business';
const REPLY_TO = 'accounts@yourdomain.com';
const OWNER_EMAIL = 'accounts@yourdomain.com';
const CURRENCY = 'USD';
const RESERVE_QUOTA = 1; // keep 1 email for the owner summary
function dayNumber_(date, tz) {
const iso = Utilities.formatDate(date, tz, 'yyyy-MM-dd');
const [y, m, d] = iso.split('-').map(Number);
return Date.UTC(y, m - 1, d) / 86400000;
}
function isFilled_(val) {
if (val instanceof Date) return !isNaN(val.getTime());
if (typeof val === 'string') return val.trim().length > 0;
if (typeof val === 'boolean') return val;
if (typeof val === 'number') return isFinite(val) && val !== 0;
return false;
}
function parseAmount_(raw) {
if (typeof raw !== 'number' || !isFinite(raw)) {
return { ok: false, reason: 'BAD_AMOUNT' };
}
if (raw <= 0) {
return { ok: false, reason: 'NON_POSITIVE_AMOUNT' };
}
return { ok: true, amount: raw };
}
function parseEmail_(raw) {
const s = String(raw || '').trim();
if (!s || /[\s,;]/.test(s)) {
return { ok: false, reason: 'BAD_EMAIL' };
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(s)) {
return { ok: false, reason: 'BAD_EMAIL' };
}
return { ok: true, email: s };
}
function parseLastSent_(raw) {
if (raw === '' || raw === null || raw === undefined) {
return { ok: true, stage: 0 };
}
if (typeof raw === 'number') {
if (!Number.isInteger(raw) || raw < 0) {
return { ok: false, reason: 'BAD_LOG' };
}
return { ok: true, stage: raw };
}
const s = String(raw).trim();
if (!s) return { ok: true, stage: 0 };
if (s.indexOf('SENDING:') === 0) {
return { ok: false, reason: 'STUCK_SENDING' };
}
if (s.indexOf('FAILED:') === 0) {
return { ok: false, reason: 'PREVIOUS_FAILURE' };
}
if (/^\d+$/.test(s)) {
return { ok: true, stage: Number(s) };
}
return { ok: false, reason: 'BAD_LOG' };
}
function evaluateRow_(row, rowNum, todayNum, tz) {
const [
inv, client, email, amt, due, paid, , , lastSent, hold
] = row;
const invoice = String(inv || '').trim();
if (!invoice || isFilled_(paid)) return { action: 'IGNORE' };
if (isFilled_(hold)) return { action: 'HOLD', rowNum, invoice };
if (!(due instanceof Date) || isNaN(due.getTime())) {
return { action: 'FLAG', rowNum, invoice, reason: 'BAD_DATE' };
}
const daysOverdue = todayNum - dayNumber_(due, tz);
const stage = STAGES.find(s => daysOverdue >= s);
if (!stage) return { action: 'IGNORE' };
const log = parseLastSent_(lastSent);
if (!log.ok) {
return { action: 'FLAG', rowNum, invoice, reason: log.reason };
}
if (stage <= log.stage) return { action: 'IGNORE' };
const money = parseAmount_(amt);
if (!money.ok) {
return { action: 'FLAG', rowNum, invoice, reason: money.reason };
}
const addr = parseEmail_(email);
if (!addr.ok) {
return { action: 'FLAG', rowNum, invoice, reason: addr.reason };
}
return {
action: 'SEND',
rowNum,
invoice,
client: String(client || '').trim() || 'there',
email: addr.email,
amount: money.amount,
due,
daysOverdue,
stage,
};
}
Notice isFilled_ on column F (Paid date) and column J (Hold). A string of spaces returns false, so an accidental spacebar tap in Paid date no longer marks an invoice paid. A valid Date, a TRUE checkbox, or a non-blank text note like "Disputed" returns true.
Notice also the order inside evaluateRow_: BAD_DATE is checked as soon as an invoice is unpaid and not on hold, even before stage calculation, because a text due date can never reach stage 3 on its own. Once daysOverdue reaches a stage, parseLastSent_ runs before parseAmount_ and parseEmail_ so an already-sent row does not nag the owner every day.
Block 2: lock, claim with flush, isolated sends, and owner summary
This is the only block that reads the sheet, writes column I, and calls GmailApp.sendEmail.
Three details separate it from the original loop:
-
Script lock first. Google's LockService reference states that
LockService.getScriptLock()"gets a lock that prevents any user from concurrently running a section of code." The rows are read only after the lock is acquired, so a second overlapping run sees whatever column I values the first run flushed. -
Claim and flush before sending. Before calling
GmailApp.sendEmail, the script writesSENDING:<stage>:<ISO timestamp>into column I and callsSpreadsheetApp.flush()("Applies all pending Spreadsheet changes" in Google's SpreadsheetApp reference). After a successful send, it overwrites the cell with the numeric stage and flushes again. IfsendEmailthrows, thecatchblock writesFAILED:<stage>:<ISO timestamp>, flushes, logs the row inissues, and moves on to the next client. -
Reserve one quota slot for yourself. Google's published Apps Script quotas list 100 email recipients per day for consumer Gmail accounts and 1,500 per day for Google Workspace accounts, and
MailApp.getRemainingDailyQuota()returns how many recipients remain for the day across all scripts on that account. Stopping client sends whenremaining <= RESERVE_QUOTA(1) keeps the final slot free sosendOwnerReport_can tell you the run stopped mid-sheet instead of going quiet.
function sendOverdueReminders() {
const lock = LockService.getScriptLock();
if (!lock.tryLock(10000)) {
console.warn('Another reminder run is active; exiting.');
return;
}
try {
const ss = SpreadsheetApp.getActive();
const sheet = ss.getSheetByName(SHEET_NAME);
if (!sheet) {
console.warn('Missing sheet: ' + SHEET_NAME);
return;
}
const rows = sheet.getDataRange().getValues();
const tz = ss.getSpreadsheetTimeZone();
const now = new Date();
const todayNum = dayNumber_(now, tz);
const stamp = now.toISOString();
const issues = [];
let sentCount = 0;
for (let i = 1; i < rows.length; i++) {
const item = evaluateRow_(rows[i], i + 1, todayNum, tz);
if (item.action === 'IGNORE' || item.action === 'HOLD') {
continue;
}
if (item.action === 'FLAG') {
issues.push(item);
continue;
}
if (MailApp.getRemainingDailyQuota() <= RESERVE_QUOTA) {
issues.push({
rowNum: item.rowNum,
invoice: item.invoice,
reason: 'QUOTA_STOPPED',
});
break;
}
const logCell = sheet.getRange(item.rowNum, 9);
logCell.setValue('SENDING:' + item.stage + ':' + stamp);
SpreadsheetApp.flush();
try {
const dueText = Utilities.formatDate(
item.due, tz, 'd MMM yyyy'
);
const msg = buildMessage_(item.stage, {
client: item.client,
invoice: item.invoice,
amount: item.amount,
dueText,
daysOverdue: item.daysOverdue,
});
GmailApp.sendEmail(item.email, msg.subject, msg.body, {
name: BUSINESS_NAME,
replyTo: REPLY_TO,
});
logCell.setValue(item.stage);
SpreadsheetApp.flush();
sentCount++;
} catch (err) {
logCell.setValue('FAILED:' + item.stage + ':' + stamp);
SpreadsheetApp.flush();
issues.push({
rowNum: item.rowNum,
invoice: item.invoice,
reason: 'SEND_FAILED: ' + err.message,
});
}
}
if (issues.length > 0) {
sendOwnerReport_(issues, sentCount);
}
} finally {
lock.releaseLock();
}
}
function buildMessage_(stage, d) {
const amt = CURRENCY + ' ' + d.amount.toFixed(2);
const sign = '\n\nKind regards,\n' + BUSINESS_NAME;
if (stage === 3) {
return {
subject: 'Friendly reminder: invoice ' + d.invoice,
body: 'Hi ' + d.client + ',\n\nA quick note that invoice '
+ d.invoice + ' for ' + amt + ' was due on ' + d.dueText
+ '. If it has already been paid, thank you and please '
+ 'ignore this message.' + sign,
};
}
if (stage === 7) {
return {
subject: 'Invoice ' + d.invoice + ' is '
+ d.daysOverdue + ' days overdue',
body: 'Hi ' + d.client + ',\n\nInvoice ' + d.invoice
+ ' for ' + amt + ' (due ' + d.dueText
+ ') still shows as unpaid on our side. Could you let us '
+ 'know when we can expect payment, or whether anything '
+ 'is holding it up?' + sign,
};
}
return {
subject: 'Second notice: invoice ' + d.invoice + ' overdue',
body: 'Hi ' + d.client + ',\n\nInvoice ' + d.invoice
+ ' for ' + amt + ' is now ' + d.daysOverdue
+ ' days past its due date of ' + d.dueText
+ '. Please arrange payment this week, or reply so we can '
+ 'agree a date. If there is a problem with the invoice, '
+ 'tell us and we will sort it out straight away.' + sign,
};
}
function sendOwnerReport_(issues, sentCount) {
if (MailApp.getRemainingDailyQuota() < 1) {
console.warn('No quota left for owner report.');
return;
}
const lines = issues.map(
x => 'Row ' + x.rowNum + ' (' + x.invoice + '): ' + x.reason
);
const subject = 'Invoice reminders: ' + issues.length
+ ' row(s) need attention (' + sentCount + ' sent)';
const body = 'The daily reminder run skipped or failed these rows:'
+ '\n\n' + lines.join('\n')
+ '\n\nFix the cell (or clear SENDING:/FAILED: after checking '
+ 'Sent Mail) before the next run.';
GmailApp.sendEmail(OWNER_EMAIL, subject, body, {
name: BUSINESS_NAME,
});
}
If every row is clean and every reminder sends, issues stays empty and sendOwnerReport_ never fires. On a messy morning like our seven-invoice probe, you get one concise email listing each row number, invoice ID, and exact reason code (BAD_AMOUNT, NON_POSITIVE_AMOUNT, BAD_LOG, BAD_DATE, BAD_EMAIL, STUCK_SENDING, PREVIOUS_FAILURE, SEND_FAILED, or QUOTA_STOPPED).
Block 3: daily trigger setup with timezone check
Google's ClockTriggerBuilder.atHour(hour) documentation notes that the trigger runs in the script's time zone, whereas dayNumber_ calculates overdue calendar days using ss.getSpreadsheetTimeZone(). Google's Session.getScriptTimeZone() reference explicitly warns that spreadsheets have a separate time zone from the script.
If your sheet is set to America/New_York and the script stayed on UTC, a 9am UTC trigger fires at 4am or 5am New York time, and near midnight the two zones disagree on what day it is. installDailyTrigger deletes only the current user's old sendOverdueReminders triggers, creates one daily trigger at 9am, and logs a warning when the two time zones differ.
function installDailyTrigger() {
ScriptApp.getProjectTriggers()
.filter(t => t.getHandlerFunction() === 'sendOverdueReminders')
.forEach(t => ScriptApp.deleteTrigger(t));
ScriptApp.newTrigger('sendOverdueReminders')
.timeBased()
.everyDays(1)
.atHour(9)
.create();
const sheetTz = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
const scriptTz = Session.getScriptTimeZone();
if (sheetTz !== scriptTz) {
console.warn(
'Timezone mismatch: sheet is ' + sheetTz
+ ', script trigger uses ' + scriptTz + '.'
);
}
}
One limitation documented by Google in the triggers guide still applies here: ScriptApp.getProjectTriggers() returns only triggers owned by the current user, so running installDailyTrigger() from two different Google accounts creates two daily triggers. With Block 2 in place, the script lock plus SENDING: and flushed stage writes stop the second trigger from sending duplicate emails, though you should still keep one dedicated or shared mailbox as the single trigger owner. (We explored that two-account trigger behaviour in detail in our Apps Script triggers guide.)
How this breaks six weeks later
Passing unit tests on day one is easy. Most receivables scripts fail a month or two later from routine team changes:
-
Column insertion shifts hardcoded indexes. Column I (
9) is hardcoded insheet.getRange(item.rowNum, 9)and in the destructuring line ofevaluateRow_. If someone inserts aCurrencyorPO Numbercolumn in front ofLast reminder, the script starts writingSENDING:3:...into the wrong column. Either protect the header row or resolve column numbers by header name if non-technical teammates edit the layout often. -
The trigger owner leaves the company. Installable time-driven triggers run under the account that created them. When that employee's Workspace account is suspended, reminders stop with no error in the sheet. Install the trigger from a shared or role mailbox (
accounts@) and monitor that inbox. -
Shared daily email quota.
MailApp.getRemainingDailyQuota()counts recipients across every Apps Script running on that Google account, not just this file. If a marketing or order-notification script burns 95 of 100 consumer emails at 8am, your 9am receivables run stops after four invoices and emails youQUOTA_STOPPED. -
Forgotten
Holdflags. Column J stops awkward reminders during a dispute, which is the right behaviour, but nothing automatically clears aHoldcell when the dispute closes. Add a simple conditional format on column J (or filter byHoldonce a week) so paused invoices do not age into write-offs.
What I tested, and what I did not
All 29 tests and 38 deliberate code mutations were run locally in Node 24 against mocked Apps Script services (SpreadsheetApp, GmailApp, MailApp, LockService, ScriptApp, Session, and Utilities.formatDate backed by Intl.DateTimeFormat).
-
Tested and measured: 5 tests pin the original 75-line script's behaviour (
USD NaN,USD -250.00,"3 days"resend, mid-loop crash on semicolon email, space inPaid date). 24 tests cover the three new blocks across every helper, exact stage boundaries (days 0, 2, 3, 6, 7, 13, 14, 30), US daylight-saving fall-back (25-hour day inAmerica/New_York), claim-and-flush ordering beforesendEmail, simulated mid-send crash andSTUCK_SENDINGfollow-up, isolated row failure, lock contention, missing tab, quota reservation at 2 and 0, and trigger timezone mismatch. -
Time zones: The full 29-test suite passed under
TZ=UTC,TZ=Europe/Istanbul, andTZ=America/Los_Angeles. -
Mutation check: I introduced 38 deliberate single-point bugs into the three blocks (flipping stage order, removing
flush(), disablingHold, droppingisFilled_trimming, removing quota reservation, weakening email delimiters). On the first pass, 37 of 38 failed; one delimiter check survived because existing bad-email tests already had two@signs. Adding trailing-semicolon and local-comma email cases brought it to 38 of 38 killed across 21 distinct first-failing tests. - Code extraction: The three code blocks above were extracted back out of this article and run directly against the same 29 tests (29/29 passed).
-
Not tested: I have not run this script inside a live Google Sheets workbook against real
GmailApp.sendEmailcalls, realLockServicecontention between two live Google executions, or real Gmail bounce/deliverability rules. The mock's email rejection rule simulates Gmail rejecting semicolons and malformed addresses; Gmail's actual server-side validation and throttling behaviour were not measured.
Wrapping up
An internal report script with a small bug annoys your team; a payment reminder script with a small bug emails your customer USD NaN or chases them for a credit note. Validate the row strictly, write and flush SENDING: before touching GmailApp, isolate every send in try/catch, and route every bad row into one daily owner summary.
The original sheet formulas, conditional formatting setup, ageing view, and full walkthrough of when to stay on a sheet vs move to a dedicated receivables system are on the MageSheet blog. If you still need to generate the invoices themselves before tracking them, start with our Google Sheets invoice template.
Drafted with AI help; the code was run and tested, and every number comes from those tests.


Top comments (0)