Extract Emails

extractEmails(text) returns every email address found in a string, lowercased, de-duplicated, in the order first seen. It returns [] when there are none, including for null or an empty string.

When to use

  • A pasted blob of text (an email thread, a signature block, a CSV pasted into one cell) with addresses scattered through it
  • Getting one address per row when REGEXEXTRACT would return only the first match
  • Building a clean list before you compare it with a sheet using Normalize Email

How to use this snippet

The pattern is practical, not a full RFC 5322 parser. It finds name@domain.tld shapes, strips a trailing period or angle bracket, and skips text like foo@bar with no top-level domain. Because it only looks at the shape, a file name such as logo@2x.png also matches, so filter those out if your text can contain them.

/** * Return every unique email address in text, lowercased, in the order first * found. Returns [] when there are none. Not a full RFC parser: it matches * the usual name@domain.tld shape only. * * @param {string} text * @return {string[]} */ function extractEmails(text) { var s = text == null ? '' : String(text); var found = s.match(/[A-Za-z0-9._%+\-]+@[A-Za-z0-9\-]+(?:\.[A-Za-z0-9\-]+)*\.[A-Za-z]{2,}/g) || []; var seen = {}; var out = []; for (var i = 0; i < found.length; i++) { var email = found[i].replace(/^[.\-]+/, '').toLowerCase(); if (!email || seen[email] === true) continue; seen[email] = true; out.push(email); } return out; }

Example

function emailsFromCellToRows() { var sheet = SpreadsheetApp.getActive().getSheetByName('Paste'); var blob = sheet.getRange('A1').getValue(); var emails = extractEmails(blob); var out = SpreadsheetApp.getActive().getSheetByName('Emails') || SpreadsheetApp.getActive().insertSheet('Emails'); out.getRange('A:A').clearContent(); if (!emails.length) return; out.getRange(1, 1, emails.length, 1).setValues(emails.map(function (e) { return [e]; })); }

Notes

  • Lowercasing is for matching and de-duplicating. If you need the original capitalization for display, keep the source text.
  • Display names (Ada Lee <ada@example.com>) are dropped; only the address is returned.
  • A trailing comma, semicolon, or period after an address is not part of it.

Happy Coding!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free snippets — plus optional Co-Pilot when you want a boost (Day Pass — $3, or 1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension