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 <firstname.lastname@example.org>, 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 = 'email@example.com' m.display_name = 'Super <@>, Name' end.to_s # Outputs: "\"Super <@>, Name\" <firstname.lastname@example.org>"
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 = 'email@example.com' m.display_name = 'Super <@>, Name' end.to_s mail to: 'firstname.lastname@example.org', from: user_address end end