Sending mail from Rails through Google SMTP

I just ran into a problem configuring a Rails app to deliver email through Google’s SMTP servers. ActionMailer doesn’t support TLS/SSL which is required by Google. Fortunately, the action_mailer_optional_tls plugin provides this functionality.

I wanted to host my SMTP settings in an external YAML file so I wouldn’t end up checking my username and password into the repository. (The YAML file is placed on the production server and a softlink is created during each deploy.) For some reason, I kept getting “connection refused” messages whenever I tried to send email with this configuration:

# smtp.yml
production:
  address: smtp.gmail.com
  port: 587
  tls: true
  domain: foo.com
  authentication: :plain
  user_name: someone@foo.com
  password: secret

# production.rb
smtp = YAML::load(File.open("#{RAILS_ROOT}/config/smtp.yml"))
ActionMailer::Base.smtp_settings = smtp[Rails.env]

The problem was the hash returned by YAML. The keys were strings, whereas ActionMailer was expecting the keys to be symbols. The fix was to make the hash use indifferent access:

...
ActionMailer::Base.smtp_settings = smtp[Rails.env].with_indifferent_access

That cleared up the “connection refused” problem. Now my app is sending email like a champ.

6 thoughts on “Sending mail from Rails through Google SMTP

  1. Just remember that Google limits you to 500 outgoing emails per day.

    Worries of running over the quota used to keep me up at night, so now I use a third party service for outgoing email. I still use Google for incoming mail.

  2. Pingback: A Fresh Cup » Blog Archive » Double Shot #228

  3. Because I’ve received several emails in reply to my previous comment, I should mention that the service I use is AuthSMTP:

    http://authsmtp.com/

    It’s quite affordable and has worked reliably from ActionMailer for the past few months that I’ve been using it.

  4. I’m curious if sending mail through a non local mail server would slow down your rails app. Would it reduce blocking to hand off outgoing mail to a local postfix and have postfix send the mail on to the non-local mail relay? Obviously keeping all the code and configuration in rails keeps things simpler and makes for a much easier deployment.

  5. Pingback: The Links Have Built Up…Link Dump Time! « IS Department

Comments are closed.