Extract Name and Email Address from Gmail Header
The Gmail Extractor lets you extract both the name and the email address of the sender from the email message. Here’s a JavaScript regex that parses the name (if available) and the email address from the sender / to field of an email message.
The email addresses can be available in the email message header fields in multiple formats. If the name is present, the email is enclosed in angle brackets. There is also an alternate simple form, specified in RFC 2822 spec, where the email address appears alone, without the recipient’s name or the angle brackets. The regex takes care of them both.
function parseEmailHeader(message) {
var header = message.getFrom().trim();
// 1. John Miranda <john@gmail.com>
// 2. john@gmail.com
var extract = { name: '', email: '' };
var emails = header.match(/[^@<\s]+@[^@\s>]+/g);
if (emails) {
extract.email = emails[0];
}
var names = header.split(/\s+/);
if (names.length > 1) {
names.pop();
extract.name = names.join(' ').replace(/"/g, '');
}
Logger.log(extract);
}
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory