Friday, January 11, 2008

How To: Use GMail as your mail server for Rails 2.0!


If you’re trying to set up ActionMailer with Google’s SMTP server, you may be running into some issues. In this post I explain a way to get ActionMailer chugging away with google!

Google provides a set of tools for your domain absolutely free. It’s called Google Apps1. One of my favorite tools to take advantage of is: GMail for your domain. Some reasons to use their mail server:

  1. Reduces load on your server (You no longer need a mailer daemon)
  2. Reduces storage consumption on your server
  3. It’s free
  4. Google is reliable

An Attempt

When most people try to get gmail to work as their mail server with ActionMailer, they try something like this:

ActionMailer::Base.smtp_settings = {
    :address  => "smtp.gmail.com",
    :port  => 465,
    :user_name  => "do_not_reply@domain.com",
    :password  => "some_password",
    :authentication  => :login
  }

Unfortunately, this doesn’t work as Gmail requires some funky security tunneling to authenticate ( TLS ). However, a plugin that was released by Marc Chung2, SMTP_TLS, solves the issue. This plugin was made for Rails 2.0.

Grab it

Download it to get started:

  cd /your_rails_app/vendor/plugins
  svn export https://openrain.com/opensource/public/rails/plugins/action_mailer_tls action_mailer_tls

For some reason, script/plugin install doesn’t work. I solved the issue by doing a svn export.

smtp_gmail.rb

Great, now add the file smptp_gmail.rb to your config/initializers folder and put the following in it:

require "smtp_tls"
 
  mailer_config = File.open("#{RAILS_ROOT}/config/mailer.yml")
  mailer_options = YAML.load(mailer_config)
  ActionMailer::Base.smtp_settings = mailer_options

Mailer.YML

In your config folder, create a file named “mailer.yml” and put the required information in it:

  ---
    :address: smtp.gmail.com
    :port: 587
    :user_name: your_gmail_username@yourdomain.com
    :password: your_gmail_username_password
    :authentication: :plain

After that, you should be gold!

Thanks to Marc for his hard work on releasing a very helpful plugin!

  1. Google Apps []
  2. marc [dot] chung [at] openrain [dot] com []
 

0 comments: