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 is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻