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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With