How can I properly parse an email address with name?
Problem
I'm reading Email headers (in Node.js, for those keeping score) and they are VARY varied. E-mail addresses in the to
field look like:
"Jake Smart" , [email protected], "Development, Business"
and a variety of other formats. Is there any way to parse all of this out?
Here's my first stab:
- Run a
split()
on-
to break up the different people into an array - For each item, see if there's a
or
"
. - If there's a
, then parse out the email
- If there's a
"
, then parse out the name - For the name, if there's a
,
, then split to get Last, First names.
If I first do a split on the ,
, then the Development, Business
will cause a split error. Spaces are also inconsistent. Plus, there may be more e-mail address formats that come through in headers that I haven't seen before. Is there any way (or maybe an awesome Node.js library) that will do all of this for me?
Related Articles
Solution
There's a npm module for this - mimelib (or mimelib-noiconv if you are on windows or don't want to compile node-iconv)
npm install mimelib-noiconv
And the usage would be:
var mimelib = require("mimelib-noiconv");
var addressStr = '[email protected], "Development, Business" ';
var addresses = mimelib.parseAddresses(addressStr);
console.log(addresses);
// [{ address: '[email protected]', name: '' },
// { address: '[email protected]', name: 'Development, Business' }]
Discussion
View additional discussion.