granth green sumo

turkey sandwiches!

Photo Photo Photo Photo Photo Photo

Gmail SMTP for Rails 8 November 2008

rails, mail, gmail

If you have a Google Apps account, you can use Gmail for the outgoing mail of your Rails app. However, Gmail requires STARTTLS to be enabled for its SMTP server. There is a plug-in that patches Net::SMTP to add STARTTLS support, but it’s broken in Ruby 1.8.7. (You’ll get an error about check_auth_args taking two arguments, not three.) The good news is that Ruby 1.8.7’s Net::SMTP includes its own support for STARTTLS! We just need to enable it in Rails.

My patch has been committed to Rails, but isn’t yet in a released version. You can patch Rails 2.1.2 with this code:

class ActionMailer::Base
  def perform_delivery_smtp(mail)
    destinations = mail.destinations
    mail.ready_to_send
    sender = mail['return-path'] || mail.from

    smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port])
    smtp.enable_starttls_auto if smtp.respond_to?(:enable_starttls_auto)
    smtp.start(smtp_settings[:domain], smtp_settings[:user_name], smtp_settings[:password],
               smtp_settings[:authentication]) do |smtp|
      smtp.sendmail(mail.encoded, sender, destinations)
    end
  end
end

Stick that in an initializer.

Your Rails SMTP settings should be like this:

ActionMailer::Base.smtp_settings = {
  :address        => "smtp.gmail.com",
  :port           => 587,
  :domain         => "example.com",
  :authentication => :plain,
  :user_name      => "username@example.com",
  :password       => "password"
}

Gmail rewrites the From header in emails, so if you want to send mail from a different address, you’ll have to add another account at your domain.

previously: Trailing Whitespace