Rails: Gmail Reply-To on Contact Form Email

— 2012-01-18

Most websites have a contact form for visitors to fill out a message that is then e-mailed to the owner or support contact for the website.

When working with a Rails app that will be hosted in a cloud environment that does not supply outbound email delivery it can be convenient to use a Gmail (or Google Apps) account at first for outbound delivery.

The trouble is that Google’s SMTP server will rewrite the email address set in the email message to match the address of the account. You can add verified alias emails to your Gmail account, but obviously you cannot do that for all of your website visitors’ addresses.

Suppose your website’s account is my_great_rails_app@gmail.com and you do something like the following in your application’s mailer:

sender_email_address = "website_user@example.com"
mail( :to => "your_email@example.com",
      :from => sender_email_address,
      :subject => “Message from Your Website")

When you get the message it will be from my_great_rails_app@gmail.com and not from website_user@example.com. Worse, if you did not think to include a copy of the sender’s email in the body of the message you will have no record of who sent it. That’s just not good!

The easiest solution is to set the reply-to header like this:

sender_email_address = "website_user@example.com"
mail( :to => "your_email@example.com",
      :from => sender_email_address,
      :’reply-to’ => sender_email_address,
      :subject => “Message from Your Website")

Now the emails from your website will still be from my_great_rails_app@gmail.com, but when you hit reply in your e-mail client your message will be addressed to website_user@example.com. So you can reply without any extra work.

I hope this helps.

Comments

Frank Rietta

After posting this, I learned that you can also use the :reply_to symbol as documented in ActionMailer http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail.

Lots of options :-)

Frank Rietta

I wanted to add, some might find the syntax for symbols in Ruby a little tricky. :reply-to will not work, but both

"reply-to".to_sym

and

:'reply-to'

are exactly the same. For instance in Rails Console or IRB instance the following will return true:

"reply-to".to_sym == :'reply-to'
=> true