Vladimir Sarić wrote this on May 2, 2012
Parsing email fields
On one of our projects we use CloudSponge to allow users to import their address books and contact their friends via bulk email. CouldSponge really simplifies this process, but you still might have to parse the string that CloudSponge returns, i.e.:
"John Doe <firstname.lastname@example.org>, Jimmy Hendrix <email@example.com>"
As we can see, when importing from an address book, it’s likely that an email address will be accompanied with additional info, which is obviously, in this case, the recipient’s real name.
Now, even though ActionMailer supports email addresses with full name specified, what if we wish to record those email addresses without the full name?
The obvious solution is to use a regular expression to extract just the email addresses. But, since I personally dislike regular expressions, even though I know they are very powerful, I decided to see if there’s another.
Luckily, the gem has exactly the tool I needed, in the form of Mail::ToField class.
emails_string = "John Doe <firstname.lastname@example.org>, Jimmy Hendrix <email@example.com>" emails = Mail::ToField.new(emails_string, "utf-8") emails.addresses # => ["firstname.lastname@example.org", "email@example.com"]
Notice that we can specify the charset, which is by default @‘utf-8’@.
Also, be careful. This does not validate the email addresses i.e.:
emails_string = "John Doe <firstname.lastname@example.org>, foobarqwerty" emails = Mail::ToField.new(emails_string) emails.addresses # => ["email@example.com", "foobarqwerty"]
Of course, the Mail gem has a lot more features, but before this, I had no idea how much utilities it provides. Plus, since it’s a dependency of ActionMailer, most of us likely already have it in our app’s gem bundle.