You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

测试net/smtp库时遭遇OpenSSL::SSL::SSLError错误求助

解决Net::SMTP发送邮件时的SSL连接错误

嘿,这个OpenSSL::SSL::SSLError我之前帮不少开发者排查过,核心问题大概率是SSL连接的配置和雅虎SMTP服务器的要求不匹配。咱们一步步来解决:

错误原因分析

SSL_connect returned=1 errno=0 state=unknown state: unknown protocol 这个错误通常是这几种情况导致的:

  • 你在不支持SSL的端口上强制发起SSL连接(比如误用了默认的25端口)
  • SSL协议版本不兼容(比如服务器要求TLS 1.2+,但代码用了旧的SSL版本)
  • Net::SMTP的SSL启用方式不正确

雅虎SMTP服务器的正确配置

雅虎的SMTP服务器标准配置是:

  • 服务器地址:smtp.mail.yahoo.com
  • 端口选择:
    • 465:直接使用SSL连接
    • 587:使用STARTTLS升级连接(更推荐)
  • 认证方式:需要用户名(你的雅虎邮箱)和密码(如果开启了两步验证,得用应用专用密码)

修正后的代码示例

方式1:用465端口直接SSL连接

require 'net/smtp'

message = %q{
From: Private Person <me@privacy.net>
To: myself <username@yahoo.com>
Subject: SMTP e-mail test

This is a test e-mail message.
}

begin
  smtp = Net::SMTP.new('smtp.mail.yahoo.com', 465)
  smtp.enable_ssl # 启用SSL
  smtp.start('smtp.mail.yahoo.com', 'username@yahoo.com', 'your_password', :login) do |smtp|
    smtp.send_message(message, 'me@privacy.net', 'username@yahoo.com')
  end
  puts "邮件发送成功!"
rescue StandardError => e
  puts "发送失败:#{e.message}"
end

方式2:用587端口+STARTTLS(更推荐)

require 'net/smtp'

message = %q{
From: Private Person <me@privacy.net>
To: myself <username@yahoo.com>
Subject: SMTP e-mail test

This is a test e-mail message.
}

begin
  smtp = Net::SMTP.new('smtp.mail.yahoo.com', 587)
  smtp.enable_starttls_auto # 自动启用STARTTLS
  smtp.start('smtp.mail.yahoo.com', 'username@yahoo.com', 'your_password', :login) do |smtp|
    smtp.send_message(message, 'me@privacy.net', 'username@yahoo.com')
  end
  puts "邮件发送成功!"
rescue StandardError => e
  puts "发送失败:#{e.message}"
end

额外注意事项

  • 如果你开启了雅虎账户的两步验证,直接用登录密码会失败,必须去雅虎账户设置里生成应用专用密码,用这个密码代替登录密码。
  • 确保你的Ruby版本支持较新的SSL/TLS协议(Ruby 2.5+一般没问题,旧版本可能需要手动指定协议,比如smtp.ssl_context = OpenSSL::SSL::SSLContext.new; smtp.ssl_context.min_version = OpenSSL::SSL::TLS1_2_VERSION)

内容的提问来源于stack exchange,提问作者Asarluhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:26:51