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 <john_doe@mail.com>, Jimmy Hendrix <jimmy@mail.net>"

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.

While Googling, I got an idea to check if the Mail gem by Mikel Lindsaar can save me from banging my head against the regular expression wall.

Luckily, the gem has exactly the tool I needed, in the form of Mail::ToField class.

emails_string = "John Doe <john_doe@mail.com>, Jimmy Hendrix <jimmy@mail.net>"
emails = Mail::ToField.new(emails_string, "utf-8")
emails.addresses # => ["john_doe@mail.com", "jimmy@mail.net"]

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 <john_doe@mail.com>, foobarqwerty"
emails = Mail::ToField.new(emails_string)
emails.addresses # => ["john_doe@mail.com", "foobarqwerty"]

If you need email validation, I suggest using the good old valid email regular expression together with ActiveModel::EachValidator.

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.

comments powered by Disqus

Suggested Reads

Rails Testing Handbook

A new ebook on building test-driven Rails apps with RSpec and Cucumber.

At Rendered Text, we have a long history with Ruby on Rails. Checking the blog archive reminds me that we published first posts about working with Rails way back in 2009.


Rendered Text is a software company. For questions regarding Semaphore, please visit semaphoreci.com. Otherwise, feel free to get in touch any time by sending us an email.