Saturday, March 31, 2012

Emails in Rails 3 using Amazon SES

Setting up Rails 3.2 for sending emails using Amazon's Simple Email Service (SES) is easy. You do not require any additional gem or monkey patching to make it work.

SES supports both STARTTLS over SMTP as well as TLS/SSL. The following demonstrates how to set up Rails for STARTTLS over SMTP with Amazon SES.


Prerequisites

1. If you are running rails on Mac OS X, you may need to configure OpenSSL for Ruby correctly before you can use STARTTLS. If you are using Ruby 1.9.3 and RVM, here is one way to do this:

rvm pkg install openssl
rvm reinstall 1.9.3 --with-openssl-dir=$rvm_path/usr


If you do not do this, there is a possibility that Ruby will segfault when you try to send an email.

2. Make sure you have verified your sender email address with AWS. You can only send emails with a verified email address as the sender. Go to the "Verified Senders" option on the left menu in AWS console for SES.

3. Make sure you have the AWS SMTP user name and password for authentication. Go to the "SMTP Settings" option on the left menu in AWS console for SES to set this up. You will first be prompted to create an IAM user (default: ses-smtp-user) and then you will be shown the SMTP user and password, which look like usual AWS key and secret. Note that the IAM user, i.e., ses-smtp-user is not the SMTP user that you will be using for authentication.


Configuring Rails

In config/development.rb and config/production.rb, add the following:

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
          :address => "email-smtp.us-east-1.amazonaws.com",
          :user_name => "...", # Your SMTP user here.
          :password => "...",  # Your SMTP password here.
          :authentication => :login,
          :enable_starttls_auto => true
  }


Sending an email

This is it. Now you can go ahead and create a mailer and start sending emails for fun and profit!
A sample mailer and its usage is shown below:

Create a sample mailer:

rails g mailer user_mailer

In app/mailer/user_mailer.rb:

class UserMailer < ActionMailer::Base
  # Make sure to set this to your verified sender!
  default from: "your@verifiedsender.com"  

  def test(email)
    mail(:to => email, :subject => "Hello World!")
  end
end

In views/user_mailer/test.erb:

A quick brown fox jumped over the lazy dog.

Now, launch the console and shoot off a test email:

rails c

Loading development environment (Rails 3.2.1)
1.9.3p125 :001 > UserMailer.test("your@email.com").deliver