Rails ActionMailer - format sender and recipient name/email address

Viewed 45760

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         = "info@mycompany.com"
@subject      = "Hi"
@content_type = "text/html"

But, I want to specify name as well-- MyCompany <info@mycompany.com>, John Doe <john.doe@mycompany>.

Is there a way to do that?

7 Answers
@recipients   = "\"#{user.name}\" <#{user.email}>"
@from         = "\"MyCompany\" <info@mycompany.com>"

within Rails 2.3.3 a bug within the ActionMailer was introduced. You can see the ticket over here Ticket #2340. It's resolved in 2-3-stable and master so it will be fixed in 3.x and 2.3.6.

For fixing the problem within 2.3.* you can use the code provided within the ticket comments:

module ActionMailer
  class Base
    def perform_delivery_smtp(mail)
      destinations = mail.destinations
      mail.ready_to_send
      sender = (mail['return-path'] && mail['return-path'].spec) || Array(mail.from).first

      smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
      smtp.enable_starttls_auto if smtp_settings[:enable_starttls_auto] && smtp.respond_to?(:enable_starttls_auto)
      smtp.start(smtp_settings[:domain], smtp_settings[:user_name], smtp_settings[:password],
                 smtp_settings[:authentication]) do |smtp|
        smtp.sendmail(mail.encoded, sender, destinations)
      end
    end
  end
end

Since Rails 6.1 there is a new convenient helper method on ActionMailer::Base:

ActionMailer::Base.email_address_with_name("test@test.com", "John Test with Quotes <'")
=> "\"John Test with Quotes <'\" <test@test.com>"

Inside a Mailer, it is accessible without the class-name:

mail to: email_address_with_name(user.email, user.name), ...

Under the hood it uses the Mail::Address like in the top answer.

Related