Reza Parang
Reza Parang

Reputation: 57

Access non-parsed email address with Mikel's Mail gem

I'm using Mikel's Mail gem successfully, but I'm trying to pull off the name from an email address without much luck.

If I receive 'Mikel Lindsaar ([email protected])', then I can access [email protected] but not 'Mikel Lindsaar'.

I've been using the to/cc/from methods on the mail object itself. I'm not sure how I would use the Mail::Address class in the documentation: http://www.ruby-doc.org/gems/docs/m/mail-2.5.4/Mail/Address.html

Upvotes: 2

Views: 174

Answers (1)

Nikos
Nikos

Reputation: 1062

Here is a simplified example of what you need:

mail = Mail.new do 
  from "Mikel Lindsaar <[email protected]>"
end

mail.header[:from].field.display_names #=> ["Mikel Lindsaar"]

The above is kind of awkward but works. The #field method on the header[:from] returns a Mail::FromField which is more or less a Mail::CommonAddress which in turn encapsulates a number of Mail::Addresses. Kind of complicated right? CommonAddress has a few handy methods to manipulate that list of addresses.

You could get the same FromField instance by

mail.from.instance_variable_get("@field")

Upvotes: 2

Related Questions