How to use Mail / ActionMailer 3 with GMail SMTP

Mon Mar 15 16:29:34 -0700 2010

Getting Mail (and therefore ActionMailer 3) working with GMail SMTP is crazy simple, if you know how.

The secret is actually in the Mail RDoc, but to save you looking, here you are:

Mail allows you to send emails using SMTP. This is done by wrapping Net::SMTP in
an easy to use manner.

Sending via SMTP server on Localhost

Sending locally (to a postfix or sendmail server running on localhost) requires
no special setup. Just do

Mail.deliver do
       to 'mikel@test.lindsaar.net'
     from 'ada@test.lindsaar.net'
  subject 'testing sendmail'
     body 'testing sendmail'
end

# Or:

mail = Mail.new do
       to 'mikel@test.lindsaar.net'
     from 'ada@test.lindsaar.net'
  subject 'testing sendmail'
     body 'testing sendmail'
end

mail.deliver

And your email will be fired off to your localhost SMTP server.

Sending via GMail

To send out via GMail, you need to configure the Mail::SMTP class to have the correct values, so to try this out, open up IRB and type the following:

require 'mail'
options = { :address              => "smtp.gmail.com",
            :port                 => 587,
            :domain               => 'your.host.name',
            :user_name            => '<username>',
            :password             => '<password>',
            :authentication       => 'plain',
            :enable_starttls_auto => true  }
            
Mail.defaults do
  delivery_method :smtp, options
end

The last block calls Mail.defaults which allows us to set the global delivery method for all mail objects that get created from now on. Power user tip, you don’t have to use the global method, you can define the delivery_method directly on any individual Mail::Message object and have different delivery agents per email, this is useful if you are building an application that has multiple users with different servers handling their email.

Delivering the email

Once you have the settings right, sending the email is done the same way as you would for a local host delivery default:

Mail.deliver do
       to 'mikel@test.lindsaar.net'
     from 'ada@test.lindsaar.net'
  subject 'testing sendmail'
     body 'testing sendmail'
end

Or by calling deliver on a Mail message

mail = Mail.new do
       to 'mikel@test.lindsaar.net'
     from 'ada@test.lindsaar.net'
  subject 'testing sendmail'
     body 'testing sendmail'
end

mail.deliver

Combining this with ActionMailer 3

So as ActionMailer 3 uses Mail as it’s email transport agent, all you have to do is pass the same options Hash into ActionMailer:

ActionMailer::Base.smtp_settings = {
  :address              => "smtp.gmail.com",
  :port                 => 587,
  :domain               => 'your.host.name',
  :user_name            => '<username>',
  :password             => '<password>',
  :authentication       => 'plain',
  :enable_starttls_auto => true  }
}

Hope that helps!

blogLater

Mikel

  1. Kamal Says:

    Thank you so much, i got this to work in few seconds. Using the “send via gmail” example
    Is there a way, i can use ruby “mail” to deliver to multiple recipients, which are in a flat file, or a yaml file.

    Thanks,

  2. Chithi Says:

    I came to know somewhat idea about gmail SMPT. Gmail SMPT implies simple mail transfer protocol. I wonder if the simple mail transfer protocol (SMPT) can be used with bulk mail or something like that. I am eager to know that.

  3. FlyboyArt Says:

    Really nice writings up here but I wish you would use a print.css files that allows for a nicer layout when printing. With the coming of the iPad and being able to take PDF’s along with you anywhere (without net access) to read, I would love to be able to print-to-pdf your articles and read them at my leisure on a train or something.

    Here’s a good place to get started with a nice print.css:

    http://www.alistapart.com/articles/goingtoprint/

    Thanks!, Art

  4. Emmanuel Oga Says:

    Nice and simple. Thanks for sharing!

  5. Daniel Says:

    Getting ‘Net::SMTPAuthenticationError: 530 5.7.0 Must issue a STARTTLS command first’

    Following your instructions by the letter, but when I issue mail.deliver I get the error.

    rails c
    Loading development environment (Rails 3.0.0.beta)
    ruby-1.9.1-p378 >

    options = { :address => “smtp.gmail.com”,
    :port => 587,
    :domain => ‘your.host.name’,
    :user_name => ‘’,
    :password => ‘’,
    :authentication => ‘plain’,
    :enable_starttls_auto => true }

    options[:domain] = ‘realthing’
    options[:user_name] = ‘real name’
    options[:password] = ‘blah’

    Mail.defaults do
    delivery_method :smtp, options
    end

    mail = Mail.new do
    to ‘me@me.com’
    from ‘bob@sled.com’
    subject ‘yeah, good test’
    body ‘testing :)’
    end

    mail.deliver

    Net::SMTPAuthenticationError: 530 5.7.0 Must issue a STARTTLS command first. 15sm1219728ewy.12

    from /Users/daniel/km/sio/trunk/vendor/bundle/gems/tlsmail-0.0.1/lib/net/smtp.rb:679:in `auth_plain’ from /Users/daniel/km/sio/trunk/vendor/bundle/gems/tlsmail-0.0.1/lib/net/smtp.rb:673:in `authenticate’ from /Users/daniel/km/sio/trunk/vendor/bundle/gems/tlsmail-0.0.1/lib/net/smtp.rb:488:in `do_start’ from /Users/daniel/km/sio/trunk/vendor/bundle/gems/tlsmail-0.0.1/lib/net/smtp.rb:440:in `start’ from /Users/daniel/km/sio/trunk/vendor/bundle/gems/mail-2.1.3/lib/mail/network/delivery_methods/smtp.rb:101:in `deliver!’ from /Users/daniel/km/sio/trunk/vendor/bundle/gems/mail-2.1.3/lib/mail/message.rb:1777:in `do_delivery’ from /Users/daniel/km/sio/trunk/vendor/bundle/gems/mail-2.1.3/lib/mail/message.rb:219:in `deliver’ from (irb):23 from /Users/daniel/.rvm/gems/ruby-1.9.1-p378/gems/railties-3.0.0.beta/lib/rails/commands/console.rb:47:in `start’ from /Users/daniel/.rvm/gems/ruby-1.9.1-p378/gems/railties-3.0.0.beta/lib/rails/commands/console.rb:8:in `start’ from /Users/daniel/.rvm/gems/ruby-1.9.1-p378/gems/railties-3.0.0.beta/lib/rails/commands.rb:34:in `<top (required)>’ from /Users/daniel/km/sio/trunk/script/rails:10:in `require’ from /Users/daniel/km/sio/trunk/script/rails:10:in `’
  6. Sohan Says:

    Your post has been linked at the Drink Rails Blog

  7. Daniel Says:

    Alright, sorry about the spam. I wish there’d been a preview button and I would have not posted so much :/

  8. daniel Says:

    Also following the instructions in http://guides.rails.info/action_mailer_basics.html

    gives me the same errors. help appreciated (only after setting config.action_mailer.raise_delivery_errors = true).

  9. bucheline Says:

    Alright, sorry about the spam. I wish there’d been a preview button and I would have not posted so much :/

  10. deepak Says:

    your blog is useless to the beginner Rail developer.. Completely crap..

  11. deepak Says:

    your blog is useless to the beginner Rail developer.. Completely crap..

  12. deepak Says:

    your blog is useless to the beginner Rail developer.. Completely crap..

  13. rman Says:

    Excellent code, worked right off the bat! Does anyone have any additions that would allow for looping through a list of emails?

  14. Tageendargy Says:

    Wo…Nice Blog, Nice tips, Great article!, I have recently started a blog, the information you provide on this site has helped me tremendously. Thank you for all of your time & work. Well Come Back To My Blog [url=http://www.ipadzu.net]Ipad[/url]
    http://www.ipadzu.net

  15. im Says:

    The future of ActionMailer in Rails 3 looks bright. Can you comment, though, on how to process incoming mail? As difficult as sending mail is on Rails, receiving it is even harder.

  16. B Says:

    @im – try this (from RSoC): http://github.com/titanous/mailman

  17. Scott Peterson Says:

    Here is code based on the post above that sends to multiple recipients:

    require ‘mail’

    #Set up Gmail access
    options = { :address => “smtp.gmail.com”,
    :port => 587,
    :domain => ‘localhost’,
    :user_name => ‘example@gmail.com’,
    :password => ‘passphrase’,
    :authentication => ‘plain’,
    :enable_starttls_auto => true }

    Mail.defaults do
    delivery_method :smtp, options
    end

    #import email addresses from text file
    recips = []
    IO.foreach(“testaddr.txt”) do |line|
    recips << line
    end

    #Status update
    puts “Done with readin\n”

    #Format email addresses properly with double quotes and send
    recips.each {|value|
    puts value
    baseadd = value.chomp
    address = “\”“baseadd”\""
    mail = Mail.new do
    to address
    from ‘example@gmail.com’
    subject ‘testing sendmail’
    body ‘testing sendmail’
    end
    mail.deliver

  18. Giovanni Says:

    Thanks a lot…

  19. scared o'spam Says:

    ripped?
    http://justinvadakkan.blogspot.com/2011/02/how-to-use-mail-actionmailer-3-with.html

  20. Giovanni Says:

    Thanks a lot.

  21. Zander Says:

    Thanks for writing this GEM!

    Just finished writing an automated init.d controller script that reads in emails via POP3, screens them for authorized senders, and then issues specific init.d commands on the server. Granted the idea came from Methods in Ruby… but it’s updated and re-written from scratch using your Mail Gem.

    Keep up the good work and thanks for the extra documentation on your blog.

  22. Zander Says:

    Thanks for writing this GEM!

    Just finished writing an automated init.d controller script that reads in emails via POP3, screens them for authorized senders, and then issues specific init.d commands on the server. Granted the idea came from Methods in Ruby… but it’s updated and re-written from scratch using your Mail Gem.

    Keep up the good work and thanks for the extra documentation on your blog.

    Gah, borked the web address. Feel free to delete first post of mine :)

  23. mycose Says:

    Some really quality blog posts on this internet site, saved to favorites.

  24. mowers Says:

    Wowo,Fantastic article,it’s so helpful to me,and your blog is very good,I’ve learned a lot from your blog here,Keep on going,my friend,I will keep an eye on it,One more thing,thanks for your post!welcome to [url=http://www.echeaplawnmowers.com]Lawn Mowers Buying Guide And Stories[/url].

  25. jibran Says:

    The best person to give you medical advice about liver disease is your doctor. Best thing we can do is recommend perhaps a good doctor if you need a second or third opinion. casino

  26. dfg45ty Says:

    Just finished writing an automated init.d controller script that reads in emails what are capers via POP3, screens them for authorized senders, and then issues specific init.d commands on the server. Granted the idea came from Methods in Ruby How Are Capers Used in Cooking… but it’s updated and re-written from scratch using your Mail Gem.

  27. jibran Says:

    This is a fantastic website and I can not recommend you guys enough. Full of useful resource and great layout very easy on the eyes. Please do keep up this great work. BMI

  28. traffic ticket Says:

    I will try to follow your tips for my future projects. I am sure that I will have excellent results.

  29. Collector Credit AB Says:

    Great site and a great topic as well! There are many people searching about that now they will find enough sources by your tips.

  30. how to be attractive to a woman Says:

    This is an inspirational and fantastic writing for other writers and artists to follow this website provides such valuable information.

  31. ipad case Says:

    This is a great tutorial. I am a newbie at using Actionmailer3 and this will surely get me more adept.

  32. ipad case Says:

    This is a great tutorial. I am a newbie at using Actionmailer3 and this will surely get me more adept.

  33. facebook timeline Says:

    I will use it for sure for my site. It is a good feature.

  34. pcb fab Says:

    I understand how to apply it. For me this is the best approach.

Leave a Reply