HOWTO: How send email using Gmail or Google Apps from Rails
If you are developing a Rails application that needs to send email, you probably want to have support for sending emails without having sendmail or an smtp server installed on every development machine.
Everyone who has a Gmail account has access to their SMTP server for free, but there are some caveats:
1. Google only allows secure SMTP connections and Rails does not have support for this out-of-the-box.
2. Even if you solve problem #1, you do not want to embed your gmail password in your code.
Let’s solve Issue #2 first: There are two immediate solutions
1. Create a throwaway gmail account just for your rails project.
2. Configure one of your domains for Google Apps, and create an email address purely for your Rails development (Google allows upto 200 email addresses in the free version). You can embed this username and password in your application and not worry about other folks having access to it.
Now about Issue #1:
There’s a hack called ‘smtp_tls’ to enable secure SMTP access in Rails, but I’ve had trouble finding the original blog post that described this, even though that code is available in many different places. Here’s an easy way to get it working.
1. Download ‘smtp_tls’ from here. (You can also google ‘smtp_tls’ to find it elsewhere) and copy it to your {RAILS_ROOT}/lib/
2. Edit {RAILS_ROOT}/config/environment.rb.
At the bottom of the file (after the very last line) add the following
require ‘smtp_tls’ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => “smtp.gmail.com”,
:port => “587″,
:domain => “yourdomain.com“,
:authentication => :plain,
:user_name => “username@yourdomain.com“,
:password => “yourpassword“
}
Of course, replace yourdomain.com with the domain where Google Apps is running, and username and yourpassword with the username and password that you created on that domain. Note that the :userame has to be your complete email address for Google Apps. You do not have to change the settings for :address and :port since the smtp server address does not depend on the domain that you configured Google Apps for. The :port parameter can be either 587 or 465.
If you are using a regular Gmail account, use that account’s settings for ::user_name and :password.
You can find more information about Google’s SMTP settings on their help page, but you wouldn’t need anything more than what’s described above.
That’s it! In your code, use ActionMailer like you would normally do.
Posted by Anil on February 22nd, 2009 :: Filed under Uncategorized