Sending Mail Through Gmail with Ruby's Net::SMTP
December 18th, 2007
Note: The original post had the wrong port number. It should be 587.
Setting up and maintaining a mail server can get annoying, so I’ve become a fan of using having my Ruby apps sending mail via Gmail.
For various reasons I hadn’t needed this for a while (sometimes I luck out and the deployment server has its own mailer server, maintained by Someone Other Than Me), but yesterday I wanted to have an application mail me when there is a problem, and I installed the Gmailer gem.
It didn’t work. It appeared to work, raising no errors or otherwise complaining, but mail never arrived anywhere.
A little debugging showed that the lib is using HTTP to talk to Gmail, and it seemed as if Google had changed the page routine.
If you’ve never tried this before, you may wonder why not just use the Net::SMTP library? The reason is that Google wants to talk using TLS, which Net:SMTP, out of the box, does not do.
However, after some prolonged Googling, I found a post on Nuclear Rooster that lead to a a post on Hatena::Diary with a very nice SMTP TLS mix-in.
I grabbed the code for smtp_tls.rb, pasted it into a local file, and was then able to send mail through the standard Ruby SMTP lib via smtp.gmail.com
require 'net/smtp'
require 'smtp_tls'
username = 'joeblow'
password = 'topsekrit'
msg = some_code_that_builds_my_message
Net::SMTP.start( 'smtp.gmail.com' ,
587,
'localhost.localdomain',
username,
password,
'plain' ){ |smtp|
smtp.send_message( msg,
"joe.blow999@gmail.com",
bono@number2yeahyeahyeah.org" )
}
More or less.
Anyways, it makes it a snap to send through Gmail. Note that that Gmailer code offers more than just mail sending if you need assorted other Gmail goodness. But if you just want to get a message out, this works great.
4 Responses to “Sending Mail Through Gmail with Ruby's Net::SMTP”
Sorry, comments are closed for this article.
December 19th, 2007 at 03:56 PM
Went through exactly this a little over a month ago and found the same fix as you. Glad to see it written up all proper like. ;~)
December 21st, 2007 at 11:05 AM
Thomas: I had looked into this a few times before, and was a bit surprised when I found those posts and the code. I really don’t know why I didn’t come across it sooner; sloppy Google-fu perhaps.
So I wrote it up here in the hopes that it makes it easier to find for the next person. Plus it’s really useful. I’ve been adding in E-mail notifications to assorted apps and It Just Works. :)
December 24th, 2007 at 02:13 PM
I had same problem, but I could not fix it :). I did install my own smtp server on my own server as a solution.
Thanks for useful information
Regards, Brian
December 25th, 2007 at 07:27 PM
Rails SMTP classes suck. I had similar problems before, but not on gmail.
Thanks