Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send email from Ruby program with TLS

Tags:

email

ruby

I am trying to send an email from a Ruby program. The smtp server is an Exchange 2007 server that requires me to login to send the email.

#!/usr/bin/ruby

require 'rubygems'
require 'net/smtp'

msgstr = "Test email."

smtp = Net::SMTP.start('smtp.server.com', 587, 
  'mail.server.com', 'username', 'password', :login) do |smtp|
    smtp.send_message msgstr, '[email protected]', '[email protected]'
end

When I run this I get the following error.

/usr/lib/ruby/1.8/net/smtp.rb:948:in `check_auth_continue': 
530 5.7.0 Must issue a STARTTLS command first (Net::SMTPAuthenticationError)
    from /usr/lib/ruby/1.8/net/smtp.rb:740:in `auth_login'
    from /usr/lib/ruby/1.8/net/smtp.rb:921:in `critical'
    from /usr/lib/ruby/1.8/net/smtp.rb:739:in `auth_login'
    from /usr/lib/ruby/1.8/net/smtp.rb:725:in `send'
    from /usr/lib/ruby/1.8/net/smtp.rb:725:in `authenticate'
    from /usr/lib/ruby/1.8/net/smtp.rb:566:in `do_start'
    from /usr/lib/ruby/1.8/net/smtp.rb:525:in `start'
    from /usr/lib/ruby/1.8/net/smtp.rb:463:in `start'

I can't find anything in the Ruby api for Net::SMTP referencing TLS or a STARTTLS command.

EDIT: Download smtp-tls.rb, the code doesn't change much but here is what I got to work.

#!/usr/bin/ruby

require 'rubygems'
require 'net/smtp'
require 'smtp-tls'

msgstr = <<MESSAGE_END
From: me <[email protected]>
To: you <[email protected]>
Subject: e-mail test

body of email

MESSAGE_END

smtp = Net::SMTP.start('smtp.test.com', 587, 'test.com', 'username', 'passwd', :login) do |smtp|
    smtp.send_message msgstr, '[email protected]',  ['[email protected]']
end

EDIT: Works with ruby 1.8.6

like image 880
Mark Avatar asked Jun 26 '09 15:06

Mark


1 Answers

No gem required in Ruby 1.9.3

You don't need a gem to do this (at least, not for Gmail and Ruby 1.9.3), the documentation is just terrible.

See https://stackoverflow.com/a/3559598/4376

like image 104
Nathan Long Avatar answered Sep 23 '22 12:09

Nathan Long