DEV Community

matt swanson
matt swanson

Posted on • Originally published at on

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 <>
Enter fullscreen mode Exit fullscreen mode

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.


Use email_address_with_name to add a name in-front on an email address in a standard way

ActionMailer::Base.email_address_with_name("", "Matt Swanson")
=> "Matt Swanson <>"
Enter fullscreen mode Exit fullscreen mode

This helper is available in all Rails mailers.

class UserMailer < ApplicationMailer
  default from: ''

  def welcome_email
    @user = params[:user]

      to: email_address_with_name(, @user.display_name),
      subject: 'You have a new message'
Enter fullscreen mode Exit fullscreen mode


This helper handles nil gracefully as well.

ActionMailer::Base.email_address_with_name("", nil)
=> ""
Enter fullscreen mode Exit fullscreen mode

And it handles escaping characters automatically:

ActionMailer::Base.email_address_with_name("", "Michael J. Scott")
=> "\"Michael J. Scott\" <>"

ActionMailer::Base.email_address_with_name("", 'John "Chip" Smith')
=> "\"John \\\"Chip\\\" Smith\" <>"
Enter fullscreen mode Exit fullscreen mode

Additional Resources

Rails API: ActionMailer::Base#email_address_with_name

Top comments (2)

m90 profile image
Frederik Ring

This is only tangential, but do you know if this kind of email address format is somehow specified / named? I was recently looking for libraries that would handle such addresses for me (outside of Rails) and had to come up with my own version. I still have the suspicion though I just don't know the proper name.