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

Inject is a fundamental building block

Inject is one of the fundamental, and most versatile constructs available in functional languages. It can be used to implement map, select, max, all? and a bunch of other iteration related methods. Unfortunately, many programmers are not aware of its awesome powers. This article is here to improve this fact.

Contact

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.

Rendered Text
Svetozara Miletica 10
21000 Novi Sad
Serbia