granth green sumo

turkey sandwiches!

Photo Photo Beaver wishing everyone a happy Canada Day. (These are not my kids.) St Clair Beach 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
    sender = mail['return-path'] || mail.from

    smtp =[: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)

Stick that in an initializer.

Your Rails SMTP settings should be like this:

ActionMailer::Base.smtp_settings = {
  :address        => "",
  :port           => 587,
  :domain         => "",
  :authentication => :plain,
  :user_name      => "",
  :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