Mike Rogers on a Snowmobile

Building internet safe addresses for ActionMailer using Mail::Address

Posted on

Recently I needed to send emails on behalf of my users, using their full name and email.

I could just pass their unsanitized input into a string like Full Name <name@example.com>, then hand that off to ActionMailer. However, I had a bunch of users with names that included characters such as @ and <, so I went searching for a safer solution.

What I discovered was that Mail (which ships with Rails and does the actual sending of emails) has a super handy Mail::Address class, which can build internet safe email addresses.

Example Usage

To build an internet safe address for ActionMailer, you can use the tap method like so:

Mail::Address.new.tap do |m|
  m.address = 'name@example.com'
  m.display_name = 'Super <@>, Name'
end.to_s

# Outputs: "\"Super <@>, Name\" <name@example.com>"

How to use with ActionMailer

To use this address in the "from" field in an email, just pass the output of to_s to the from argument when sending an email. Like this:

class GuestMailer < ApplicationMailer
  def get_hyped
    user_address = Mail::Address.new.tap do |m|
      m.address = 'name@example.com'
      m.display_name = 'Super <@>, Name'
    end.to_s

    mail to: 'guest@example.com', from: user_address
  end
end

This was written by Mike Rogers, a freelance Ruby on Rails developer based in London.

Share the ♥ by sharing this!

If you want to discuss this post, feel free to tweet me (@MikeRogers0) or drop me an email. Any code samples unless stated otherwise are licensed under the The MIT License (MIT). Spotted a mistake? Send me a pull request :)