Our guide to parsing emails into Google Sheets builds a free Apps Script parser: a Gmail filter puts a to-parse label on order notifications, a trigger runs parseInbound() every 5 minutes, extractOrder() pulls the order number, customer, email and total out of getPlainBody(), and the thread moves to parsed.
Before pointing more shops at it, I ran that exact code, unchanged, against mocked GmailApp, SpreadsheetApp and LockService with a small invented inbox: three orders at $55 each, the shop re-sending one confirmation, and a "has shipped" email landing in the thread of another. The sheet should hold 3 rows that add up to $165. It held 5 rows that add up to $250, and every single total was $5 short.
| Invented email (mocked Apps Script) | Article's script | With the three blocks |
|---|---|---|
Order #1042, Subtotal: $50.00 above Total: $55.00 | 1 row, total 50 | 1 row in Orders, total 55 |
Order #1043, Total: $55.00 | 1 row, total 50 | 1 row in Orders, total 55 |
| "Order #1043 has shipped", same thread, next run | 2nd row for #1043, total 50 | Order updates tab, not in Orders |
Order #1044, Total: $55.00 | 1 row, total 50 | 1 row in Orders, total 55 |
| Order #1044 confirmation re-sent, new thread | 2nd row for #1044, total 50 | Order updates tab, not in Orders |
| Orders tab after two runs | 5 rows, SUM $250 | 3 rows, SUM $165 |
None of these rows went to parse-failed. The script did what it was written to do; the inbox just contained emails it was not written for.
Why the original parser writes the wrong rows
The article's version gets several things right, and I kept all of them: a script lock, one setValues() call per run, SpreadsheetApp.flush() before relabelling, a paged GmailApp.search('label:to-parse', 0, 50), and the Gmail message ID in column A so a re-labelled thread does not write the same message twice. The problems sit one level up, in what counts as "the same order".
-
/Total:/ialso matchesSubtotal:.extractOrder()reads the total withgrab(/Total:\s*[^\d]*([\d.,]+)/i), andgrabreturns the first match. The pattern has no anchor, so thetotal:insideSubtotal: $50.00matches before the realTotal: $55.00line further down. Any notification that lists the subtotal above the total, as my test emails do, hits this. Every order in my test was written with its subtotal, and the shipping fee disappeared from the sheet without any error. - A message ID is not an order. The guide's duplicate section is right that Gmail labels live on threads:
GmailThreadhasaddLabel()andremoveLabel(), and Google'sGmailMessagereference lists neither. So when a shipping update lands in an old thread, the filter putsto-parseback on it. The ID check correctly skips the original confirmation. But the update is a new message with a new ID, it also containsOrder #1043and aTotal:line, soextractOrder()succeeds and order 1043 gets a second row. - A resend is a new thread. When the shop sends the confirmation again (order edited, customer clicked "resend") and Gmail puts it in a new thread, the label path starts fresh. New thread, new message ID, same order number: another duplicate row. On a weekly revenue
SUM()over column G, two duplicates and a missing shipping fee per row turned $165 into $250.
Two smaller ones showed up while testing the fix. Number(total) || '' turns a legitimate $0.00 order (a 100% discount code) into a blank cell. And a European Total: 1.234,56 € becomes 1.23456 after the comma is stripped; the guide's code comment does say it assumes the 1,234.56 format, so treat that as a reminder to check your shop's locale before the first run.
The parse path
Every message now ends in exactly one of three places, and only one of them feeds your totals.
The rule behind it: the label decides which threads to read, the message ID decides which messages are new, and the order number decides which messages become order rows. Everything else is kept, on its own tab, so you can still answer "where did this row come from".
Block 1: extraction that refuses to guess
extractOrder_() replaces extractOrder(). It is a pure function (no Gmail, no Sheets), so it is easy to test, and instead of returning null it returns a reason you can read later in the sheet.
// Pure extraction: no Gmail, no Sheets. Returns a reason on failure. const MONEY_RE = /^(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d{1,2})?$/; function parseMoney_(raw) { const s = String(raw || '').trim(); if (!MONEY_RE.test(s)) return null; return Number(s.replace(/,/g, '')); } function lineValues_(body, re) { return Array.from(body.matchAll(re), m => m[1].trim()); } function extractOrder_(body) { const order = lineValues_(body, /\bOrder\s*#\s*([A-Z0-9-]+)/gi)[0]; if (!order) return { ok: false, reason: 'NO_ORDER_NUMBER' }; // Line-anchored: "Subtotal:" and "Tax total:" never match. const totals = lineValues_(body, /^[ \t]*(?:Order |Grand )?Total:[ \t]*[^\d\n]*([\d.,]+)/gim); const distinct = Array.from(new Set(totals)); if (distinct.length === 0) { return { ok: false, order, reason: 'NO_TOTAL' }; } if (distinct.length > 1) { return { ok: false, order, reason: 'AMBIGUOUS_TOTAL' }; } const total = parseMoney_(distinct[0]); if (total === null) return { ok: false, order, reason: 'BAD_TOTAL' }; const one = re => (lineValues_(body, re)[0] || ''); return { ok: true, order: order.toUpperCase(), customer: one(/^[ \t]*Customer:[ \t]*(.+)$/gim), email: one(/^[ \t]*Email:[ \t]*([^\s<>]+@[^\s<>]+)/gim), total: total, }; } The total pattern is anchored to the start of a line and only accepts Total:, Order Total: or Grand Total:, so Subtotal: and Tax total: can never match. If the email contains two different Total: values, the function stops with AMBIGUOUS_TOTAL instead of picking one. parseMoney_() only accepts 1234, 1234.5 or 1,234.56 style numbers, so 1.234,56 comes back as BAD_TOTAL rather than as 1.23456, and 0.00 stays 0. The customer pattern uses [ \t]* instead of \s*, because \s also matches a newline: with an empty Customer: line, the old pattern quietly took the next line (Email: ...) as the customer name.
Block 2: one row per order, updates on their own tab
parseInbound() keeps the article's structure and adds two sets: order numbers already in column D of Orders, and message IDs already in either Orders or Order updates.
// Orders: A id | B date | C from | D order | E customer | F email // G total const ORDERS = 'Orders'; const UPDATES = 'Order updates'; // A id | B date | C from | D order const FAILURES = 'Parse failures'; // A id | B date | C from | D reason const TODO = 'to-parse', DONE = 'parsed', FAILED = 'parse-failed'; function sheet_(ss, name) { return ss.getSheetByName(name) || ss.insertSheet(name); } function column_(sheet, col) { const last = sheet.getLastRow(); if (last < 2) return []; return sheet.getRange(2, col, last - 1, 1).getValues().flat() .map(String); } function label_(name) { return GmailApp.getUserLabelByName(name) || GmailApp.createLabel(name); } function append_(sheet, rows) { if (!rows.length) return; sheet.getRange(sheet.getLastRow() + 1, 1, rows.length, rows[0].length).setValues(rows); } function parseInbound() { const lock = LockService.getScriptLock(); if (!lock.tryLock(5000)) return; try { const ss = SpreadsheetApp.getActive(); const orders = sheet_(ss, ORDERS); const updates = sheet_(ss, UPDATES); const failures = sheet_(ss, FAILURES); const seenIds = new Set(column_(orders, 1) .concat(column_(updates, 1))); const seenOrders = new Set(column_(orders, 4)); const loggedFails = new Set(column_(failures, 1)); const todo = label_(TODO), done = label_(DONE); const failed = label_(FAILED); const newRows = [], updRows = [], failRows = []; const ok = [], bad = []; for (const thread of GmailApp.search('label:' + TODO, 0, 50)) { let threadOk = true; for (const msg of thread.getMessages()) { const id = msg.getId(); if (seenIds.has(id)) continue; const head = [id, msg.getDate(), msg.getFrom()]; const r = extractOrder_(msg.getPlainBody()); if (!r.ok) { threadOk = false; if (!loggedFails.has(id)) { failRows.push(head.concat(r.reason)); } } else if (seenOrders.has(r.order)) { updRows.push(head.concat(r.order)); // update or resend } else { newRows.push(head.concat(r.order, r.customer, r.email, r.total)); seenOrders.add(r.order); } } (threadOk ? ok : bad).push(thread); } append_(orders, newRows); append_(updates, updRows); append_(failures, failRows); SpreadsheetApp.flush(); // rows are safe before relabel ok.forEach(t => t.removeLabel(todo).removeLabel(failed) .addLabel(done)); bad.forEach(t => t.removeLabel(todo).addLabel(failed)); } finally { lock.releaseLock(); } } A message for an order that already has a row goes to Order updates (ID, date, sender, order number). That covers shipping notices in the same thread and resends in a new one. A message that fails extraction goes to Parse failures with its reason, once per message ID, and its thread gets parse-failed as before. Failed messages are not marked as seen, so after you fix a pattern and put to-parse back on the thread by hand, they are retried. A thread that later parses cleanly also loses its old parse-failed label, so the label count you alert on goes down when the problem is fixed.
The column A advice from the guide still applies to both ID columns: format them as plain text before the first run so Sheets never turns an all-digit ID into a number.
Block 3: a daily check that notices silence
The guide's "when it breaks" section recommends a daily "rows parsed today" check. Here it is, with the trigger installer.
const OWNER = 'you@yourshop.com'; const MIN_ORDERS_PER_DAY = 1; // set 0 if quiet days are normal function healthIssues_(o) { const dayAgo = o.now.getTime() - 24 * 60 * 60 * 1000; const recent = o.dates.filter(d => d instanceof Date && d.getTime() >= dayAgo).length; const issues = []; if (!o.triggerOk) issues.push('No parseInbound trigger installed.'); if (recent < o.minOrders) { issues.push('Only ' + recent + ' new order row(s) in 24h.'); } if (o.failed > 0) { issues.push(o.failed + ' thread(s) waiting in ' + FAILED + '.'); } return issues; } function dailyParseCheck() { const orders = SpreadsheetApp.getActive().getSheetByName(ORDERS); const last = orders ? orders.getLastRow() : 0; const dates = last > 1 ? orders.getRange(2, 2, last - 1, 1).getValues().flat() : []; const label = GmailApp.getUserLabelByName(FAILED); const failed = label ? label.getThreads(0, 100).length : 0; const triggerOk = ScriptApp.getProjectTriggers() .some(t => t.getHandlerFunction() === 'parseInbound'); const issues = healthIssues_({ dates, failed, triggerOk, now: new Date(), minOrders: MIN_ORDERS_PER_DAY }); if (issues.length) { MailApp.sendEmail(OWNER, 'Email parser: ' + issues.length + ' issue(s)', issues.join('\n')); } } function install() { const mine = ['parseInbound', 'dailyParseCheck']; ScriptApp.getProjectTriggers() .filter(t => mine.indexOf(t.getHandlerFunction()) >= 0) .forEach(t => ScriptApp.deleteTrigger(t)); ScriptApp.newTrigger('parseInbound').timeBased().everyMinutes(5) .create(); ScriptApp.newTrigger('dailyParseCheck').timeBased().everyDays(1) .atHour(8).create(); } healthIssues_() is pure and takes the dates from column B (the email date), the number of threads under parse-failed, and whether a parseInbound trigger exists. dailyParseCheck() emails you only when one of the three is wrong. install() deletes this project's existing parseInbound and dailyParseCheck triggers before creating new ones, so running it twice does not leave two parsers racing for the lock. Set MIN_ORDERS_PER_DAY to 0 if a day with no orders is normal for your shop, or the Sunday email becomes noise you learn to ignore.
How this breaks a few months later
- A second shop or marketplace. Order numbers are only unique per sender. If you add an Etsy filter next to a Shopify one,
#1042from each will collide, and the second becomes an "update". Prefix the order key with the source before you add a second sender. - "Order edited" with a new total. Block 2 sends it to
Order updatesand leaves the first total inOrders. That is deliberate (the sheet does not overwrite money on its own), but someone has to look at that tab. If your shop edits orders often, add the total to the update row and review the difference weekly. - The template changes. A platform update moves the total into a table, the line anchor no longer matches, and messages go to
Parse failuresasNO_TOTAL. That is the point of the reason column: you see the change on day one, not at month-end. - The account goes away. The daily check runs as the same Google account as the parser. If that account is suspended or deleted, both triggers stop, and the check cannot email you about it. Keep the parser on a shared or service mailbox that does not leave with an employee. Our earlier post on an inbound email route that skipped its own signature checkSource:https://dev.to/hayrullahkar/parse-emails-into-google-sheets-the-regex-that-read-subtotal-as-total-f0e

