(Ruby) Getting Net::SMTP working with Gmail...?

humble_coder picture humble_coder · Jul 26, 2009 · Viewed 20.6k times · Source

Does anyone have any quality (and up-to-date) information regarding sending mail via Gmail using Ruby's Net::SMTP? I've seen several examples -- most dating from 2007 to mid-2008 and none of them work for me. I need more current examples that use the most recent 1.8.7 release. I'd also appreciate if the documentation didn't only cover simple examples that no one ever really uses.

Currently I'm receiving an error:

 SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: unknown protocol

I'm not terribly familiar with SSL as regards the SMTP protocol, so this is all lost on me. Unfortunately the Net::SMTP documentation only covers the bases and doesn't provide a full list of the various potential OpenSSL::SSL contexts either so I can't try various ones.

Anyway, if anyone has any quality info on getting this to work with Gmail it would be most appreciated.

Best.

Answer

David picture David · Aug 24, 2010

Actually the below works for gmail without a plugin or a gem, at least with Ruby 1.9.1p376, but good luck finding documentation that'll tell you so:

    require 'net/smtp'

    msg = "Subject: Hi There!\n\nThis works, and this part is in the body."
    smtp = Net::SMTP.new 'smtp.gmail.com', 587
    smtp.enable_starttls
    smtp.start(YourDomain, YourAccountName, YourPassword, :login) do
      smtp.send_message(msg, FromAddress, ToAddress)
    end

YourAccountName looks like '[email protected]' & YourDomain can probably be anything you like, but I use the actual domain name.