Rails ActionMailer - format sender and recipient name/email address

Grnbeagle picture Grnbeagle · Jun 5, 2009 · Viewed 44.6k times · Source

Is there a way to specify email AND name for sender and recipient info when using ActionMailer?

Typically you'd do:

@recipients   = "#{user.email}"
@from         = "[email protected]"
@subject      = "Hi"
@content_type = "text/html"

But, I want to specify name as well-- MyCompany <[email protected]>, John Doe <john.doe@mycompany>.

Is there a way to do that?

Answer

James McKinney picture James McKinney · Nov 12, 2011

If you are taking user input for name and email, then unless you very carefully validate or escape the name and email, you can end up with an invalid From header by simply concatenating strings. Here is a safe way:

require 'mail'
address = Mail::Address.new email # ex: "[email protected]"
address.display_name = name.dup   # ex: "John Doe"
# Set the From or Reply-To header to the following:
address.format # returns "John Doe <[email protected]>"