Every vendor receipt lands in Gmail. Every Monday someone copies them into the Receipts tab by hand. You script it, put it on a trigger, and it works. Then someone clicks Run again to “make sure”, and now every receipt is in the sheet twice.
Gmail already has a perfectly good “already done” marker: labels. Search for threads that don’t have your label, write them to the sheet, and label them after the write succeeds. The label is your receipt. No label means the thread hasn’t been imported yet, and the next run picks it up.
TL;DR
- Pick one receipt label per job, e.g.
Imported/Receipts - Search with
-label:"Imported/Receipts"appended usinggetUnprocessedThreads GmailApp.searchreturns at most 500 threads per call, so page withstart/maxand cap each run- Write rows with one
setValues,SpreadsheetApp.flush(), thenmarkThreadsProcessed - Keep the thread id in a column so a crash between write and label can’t create a duplicate
Using the Apps Script editor a lot? NitroGAS drops free themes & snippets right into script.google.com — optional Co-Pilot when you want a boost.
What not to do
- Don’t label first and write second. If the write throws, those threads are labelled “done” and never imported
- Don’t rely on
newer_than:1dalone. Miss one run (or run twice) and you skip or duplicate a day - Don’t
appendRowinside the thread loop; 300 threads means 300 round trips and a timeout - Don’t call
GmailApp.search(query)with no paging and assume you got everything: you get at most 500 - Don’t label between pages. It changes what
-label:matches and shifts the offsets under you
The pattern
1. Find threads without the receipt label
From the get-unprocessed-threads snippet:
var RECEIPT_LABEL = 'Imported/Receipts';
var QUERY = 'from:billing@vendor.com has:attachment';
var threads = getUnprocessedThreads(QUERY, RECEIPT_LABEL, 300);
Under the hood it runs GmailApp.search(QUERY + ' -label:"Imported/Receipts"', start, 500) in a loop until a page comes back short or the cap is hit. Gmail does the de-dupe filtering, not your script.
2. Turn threads into rows (in memory)
function threadsToRows_(threads) {
return threads.map(function (t) {
var m = t.getMessages()[0];
return [
t.getId(), // A: thread id = your idempotency key
m.getDate(), // B
m.getFrom(), // C
m.getSubject(), // D
t.getPermalink() // E: one click back to the email
];
});
}
3. Write once, then stamp the receipt
function importVendorReceipts() {
var lock = LockService.getScriptLock();
if (!lock.tryLock(5000)) return; // a run is already in progress
try {
var threads = getUnprocessedThreads(QUERY, RECEIPT_LABEL, 300);
if (!threads.length) return;
var sheet = SpreadsheetApp.getActive().getSheetByName('Receipts');
var seen = existingThreadIds_(sheet); // Set of ids already in column A
var fresh = threads.filter(function (t) { return !seen.has(t.getId()); });
var rows = threadsToRows_(fresh);
if (rows.length) {
sheet.getRange(sheet.getLastRow() + 1, 1, rows.length, rows[0].length).setValues(rows);
SpreadsheetApp.flush();
}
// Only reached if the write didn't throw. Label ALL fetched threads,
// including ones that were already in the sheet from a crashed run.
markThreadsProcessed(threads, RECEIPT_LABEL);
} finally {
lock.releaseLock();
}
}
function existingThreadIds_(sheet) {
var last = sheet.getLastRow();
if (last < 2) return new Set();
return new Set(sheet.getRange(2, 1, last - 1, 1).getValues().map(function (r) { return String(r[0]); }));
}
The thread-id check is the belt to the label’s braces. If the execution dies right after setValues but before the label lands, the next run finds the same threads again, sees their ids already in column A, skips the write, and labels them. Same idea as Re-run your import without duplicating rows, with Gmail doing half the work.
The 500-thread cap (and why you still cap lower)
GmailApp.search(query, start, max) will not return more than 500 threads in one call. The snippet pages: start = 0, 500, 1000… until a short page. Paging is safe here because nothing gets labelled until the whole batch is written.
You still want a per-run cap (the third argument, e.g. 300):
- Reading messages is slow. 2,000 threads ×
getMessages()can eat most of the 6-minute window - A smaller batch means a smaller write and a smaller blast radius if something is off
- Leftovers stay unlabelled, so the next trigger picks them up automatically
For a one-time backfill of thousands of threads, run the same function on a 10-minute trigger until it reports zero, or add a time-budget check. For big writes, see Batch writes without timeouts.
Trigger it
function installReceiptImport() {
ScriptApp.newTrigger('importVendorReceipts').timeBased().everyHours(1).create();
}
Run that installer once (or use your existing install-once helper). The import itself is safe to run at any time: hourly, by hand, twice in a row.
Soft Co-Pilot note
NitroGAS has getUnprocessedThreads and markThreadsProcessed ready to search in the editor. If you already have a Gmail import that duplicates, paste it into Co-Pilot and ask it to switch to the receipt-label pattern with the label applied after setValues. Free core; Co-Pilot is a pass when you want the draft.
Closing checklist
- One dedicated receipt label for this job
- Search appends
-label:"…"and pages past 500 with a per-run cap - Rows built in memory, written with one
setValues, thenflush() - Label applied only after the write succeeds
- Thread id stored in the sheet and checked before writing
- Script lock so a manual run and the trigger can’t overlap
- Ran it twice in a row on a test label and got zero new rows the second time
Happy Coding!