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

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


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 'you@domain.com' & YourDomain can probably be anything you like, but I use the actual domain name.


I actually just got this working. Wrote a quick script to test it.

I was getting a different error than you were (requiring STARTTLS), I also found I had to use port 587 instead of 465.

I found the trick to get it working in a Rails plugin I found. (agilewebdevelopment.com/plugins/net_smtp_tls_support)

if you 'eval' this file (it adds tls support to the standard Net::SMTP library):

http://happiness-is-slavery.net/wp-content/rails-plugins/smtp_add_tls_support/lib/smtp_add_tls_support.rb

then run 'Net::SMTP.enable_tls()'

everything seems to work fine.

Here's my code:

require 'rubygems'require 'net/smtp'eval File.read("smtp_tls.rb")Net::SMTP.enable_tls() FROM_EMAIL = "REMOVED"PASSWORD = "REMOVED"TO_EMAIL = "REMOVED"msgstr = <<END_OF_MESSAGEFrom: Your Name <#{FROM_EMAIL}>To: my phone <#{TO_EMAIL}>Subject: text messageDate: Sat, 23 Jun 2001 16:26:43 +0900Message-Id: <unique.message.id.string@example.com>This is a test message.END_OF_MESSAGENet::SMTP.start('smtp.gmail.com', 587, 'gmail.com',                      FROM_EMAIL, PASSWORD, :plain) do |smtp|  smtp.send_message msgstr, FROM_EMAIL, TO_EMAILend

obviously, i downloaded the above mentioned file to the same directory and named it 'smtp_tls.rb'

Hope this helps!


Are you connecting to smtp.gmail.com port 465 I am assuming? .

openssl s_client -connect smtp.gmail.com:587

CONNECTED(00000003)8298:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:601:

The error looks very similar to yours. The following command does work:

 openssl s_client  -starttls smtp -connect smtp.gmail.com:587

So I think what is happening is that you do not have STARTTLS support enabled. I am not sure how to do it in ruby buy what I did find out is that the action_mailer_tls plugin allows this by patching Net::SMTP. As of Ruby 1.8.7, Net::SMTP has this support built-in.

If you are using Ruby < 1.8.7 here is the patch.