Asarluhi
Asarluhi

Reputation: 1290

OpenSSL::SSL::SSLError while testing the net/smtp library

I am trying to send emails using the net/smtp library but I receive the following error message:

SSL_connect returned=1 errno=0 state=unknown state: unknown protocol (OpenSSL::SSL::SSLError)

The code I am using is an extract from Peter Cooper's Beginning Ruby book, modified to use SSL, as required by yahoo servers:

require 'net/smtp'

message = %q{
    From: Private Person <[email protected]>
    To: myself <[email protected]>
    Subject: SMTP e-mail test

    This is a test e-mail message.
}


smtp = Net::SMTP.new('smtp.mail.yahoo.com', 587)
smtp.enable_ssl
smtp.start('example.org', '[email protected]', 'password', :login) do |s|
  s.send_message message, '[email protected]', '[email protected]'
end

I tested the above code with Ruby 2.3.1 and Ruby 2.5.1 but I keep receiving the same error message.

Upvotes: 0

Views: 560

Answers (1)

Holger Just
Holger Just

Reputation: 55833

By using Net::SMTP#enable_ssl (which is an alias to Net::SMTP#enable_tls), you are instructing the Ruby SMTP client to open a TLS tunnel as the very first step after connecting to the server. This requires the server to also support this on the used server port.

With Yahoos SMTP servers, they support this mode on port 465. With many other providers, you will see that they only support opportunistic TLS on port 587.

What happens there is that the client first starts with plain text SMTP and then negotiates with the server whether they support to update the connection to a TLS tunnel by using the STARTTLS command.

With net/smtp in Ruby, you can use Net::SMTP#enable_starttls instead.

If you are not sure of the server supports STARTTLS and you want to gracefully fallbvack to plaintext transfer of your password and the email to the server, you can also use Net::SMTP#enable_starttls_auto.

Thus, with Yahoo, you have two options:

  • you can use Net::SMTP#enable_tls on port 465
  • or you can use Net::SMTP#enable_starttls on port 587

Upvotes: 2

Related Questions