Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse email addresses for "from" and "to" fields in Ruby

In an email, it looks like a "from" or "to" field can contain one or more addresses, each address can be like "[email protected]" or "John D Jr <[email protected]>"

So a "from" field can look like any of the following:

"[email protected]"

"[email protected], Bob Blue <[email protected]>"

"Abe Allen <[email protected]>, [email protected]"

"Abe Allen <[email protected]>, Bob Blue <[email protected]>"

"Abe Allen <[email protected]>, Bob Blue <[email protected]>, [email protected]"

and so on.

I want to parse these fields, extracting each address' email if it's valid, and the name if it's present. Since I'm not familiar with the email standard, I may be missing some cases of what address fields can look like. Is there a Ruby library that can do this?

like image 309
foobar Avatar asked Aug 29 '12 22:08

foobar


1 Answers

Yes, there's a gem for this; it's called mail.

require 'mail'

addresses = []
raw_addresses = Mail::AddressList.new("Abe Allen <[email protected]>, Bob Blue <[email protected]>, [email protected]")

raw_addresses.addresses.each do |a|  
  address = {}

  address[:address] = a.address
  address[:name]    = a.display_name if a.display_name.present?

  addresses << address      
end
like image 197
deefour Avatar answered Nov 07 '22 04:11

deefour