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 <email@example.com>, then hand that off to ActionMailer. However, I had a bunch of users with names that included characters such as
<, so I went searching for a safer solution.
To build an internet safe address for ActionMailer, you can use the tap method like so:
Mail::Address.new.tap do |m| m.address = 'firstname.lastname@example.org' m.display_name = 'Super <@>, Name' end.to_s # Outputs: "\"Super <@>, Name\" <email@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 = 'firstname.lastname@example.org' m.display_name = 'Super <@>, Name' end.to_s mail to: 'email@example.com', from: user_address end end