Tip: Improving your Rails mailers with `email_address_with_name`
In almost all email programs, you can add a display name before your email address like so:
To: Matt Swanson <email@example.com>
It’s a small touch, but it is a more human-readable way of addressing an email. Rails provides a helper utility to format email addresses in this style without resorting to manual string manipulation.
email_address_with_name to add a name in-front on an email address in a standard way
ActionMailer::Base.email_address_with_name("firstname.lastname@example.org", "Matt Swanson") => "Matt Swanson <email@example.com>"
This helper is available in all Rails mailers.
class UserMailer < ApplicationMailer default from: 'firstname.lastname@example.org' def welcome_email @user = params[:user] mail( to: email_address_with_name(@user.email, @user.display_name), subject: 'You have a new message' ) end end
This helper handles
nil gracefully as well.
ActionMailer::Base.email_address_with_name("email@example.com", nil) => "firstname.lastname@example.org"
And it handles escaping characters automatically:
ActionMailer::Base.email_address_with_name("email@example.com", "Michael J. Scott") => "\"Michael J. Scott\" <firstname.lastname@example.org>" ActionMailer::Base.email_address_with_name("email@example.com", 'John "Chip" Smith') => "\"John \\\"Chip\\\" Smith\" <firstname.lastname@example.org>"
Rails API: ActionMailer::Base#email_address_with_name