Rails 6 adds ActionMailer#email_address_with_name

Taha Husain

By Taha Husain

on October 22, 2019

This blog is part of our  Rails 6 series.

When using ActionMailer::Base#mail, if we want to display name and email address of the user in email, we can pass a string in format "John Smith" <[email protected]> in to, from or reply_to options.

Before Rails 6, we had to join name and email address using string interpolation as mentioned in Rails 5.2 Guides and shown below.

1  email_with_name = %("John Smith" <[email protected]>)
2  mail(
3    to: email_with_name,
4    subject: 'Hey Rails 5.2!'
5  )

Problem with string interpolation is it doesn't escape unexpected special characters like quotes(") in the name.

Here's an example.

Rails 5.2

1
2irb(main):001:0> %("John P Smith" <[email protected]>)
3=> "\"John P Smith\" <[email protected]>"
4
5irb(main):002:0> %('John "P" Smith' <[email protected]>)
6=> "'John \"P\" Smith' <[email protected]>"
7

Rails 6 adds ActionMailer::Base#email_address_with_name to join name and email address in the format "John Smith" <[email protected]> and take care of escaping special characters.

Rails 6.1.0.alpha

1
2irb(main):001:0> ActionMailer::Base.email_address_with_name("[email protected]", "John P Smith")
3=> "John P Smith <[email protected]>"
4
5irb(main):002:0> ActionMailer::Base.email_address_with_name("[email protected]", 'John "P" Smith')
6=> "\"John \\\"P\\\" Smith\" <[email protected]>"
7
1mail(
2to: email_address_with_name("[email protected]", "John Smith"),
3subject: 'Hey Rails 6!'
4)

Here's the relevant pull request for this change.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.