Extract email addresses from text
Given a block of text with addresses scattered through it, this recipe lists each distinct address once, sorted, ready to paste into a spreadsheet or a suppression list. The text never leaves the tab, which matters when it is a customer export.
The steps
- 1
Extract matchesvia Regex Tester & Builder
Every match on its own line. The pattern accepts the address shapes that occur in practice rather than the full RFC grammar.
- 2
Remove duplicate linesvia Line Sorter & Deduplicator
Mail domains are case-insensitive and most mailboxes are treated that way too, so Ops@Example.com and ops@example.com count once.
- 3
Sort linesvia Line Sorter & Deduplicator
Alphabetical so the same domain's addresses sit together.
About the pattern
The expression matches a local part of letters, digits and the usual punctuation, an at sign, a domain of letters, digits, dots and hyphens, and a top-level domain of at least two letters. It will match addresses inside angle brackets, after a colon, or in the middle of a sentence. It will not match quoted local parts or IP-literal domains, which are valid and almost never seen. It can over-match when a full stop follows the address, since a trailing dot is not part of it; the pattern stops before the dot in that case.
When a list like this is needed
- Building a suppression list from bounce logs before a mailing.
- Finding every address mentioned in a long thread to add them to a calendar invite.
- Checking a data export for addresses that should have been anonymised, without sending the export anywhere.
For the last case, the Sensitive Data Scanner goes further: it finds phone numbers, card numbers, keys and tokens as well, and can produce a redacted copy.
Cleaning the result
Look at the first and last entries of the sorted list; that is where malformed matches gather, such as a version string or a filename that happened to contain an at sign. Remove them by hand. If the source used display names, such as Name <address>, only the address is kept.
Questions
- Is the list case-folded?
- Duplicates are found ignoring case, but the first occurrence is kept as written. Lower-case the whole list in the case converter if you need one form.
- Can I extract something else with the same steps?
- Yes. Open the regex tester from the first step, change the pattern, and the extract, dedupe and sort steps apply to phone numbers, URLs or order ids just the same.