在Ruby中,你可以使用Net::SMTP库来发送邮件。以下是一个简单的示例,演示如何使用SMTP发送邮件:
require 'net/smtp'

# 设置SMTP服务器和端口
smtp_server = 'your_smtp_server'
smtp_port = 587

# 发件人和收件人信息
from_email = 'your_email@example.com'
to_email = 'recipient@example.com'

# 设置邮件内容
message = <<END_OF_MESSAGE
From: #{from_email}
To: #{to_email}
Subject: Hello from Ruby SMTP

This is a test email sent from Ruby.
END_OF_MESSAGE

# 使用SMTP发送邮件
begin
  Net::SMTP.start(smtp_server, smtp_port) do |smtp|
    smtp.send_message(message, from_email, to_email)
  end
  puts 'Email sent successfully!'
rescue => e
  puts "Error sending email: #{e.message}"
end

请注意,你需要替换示例中的占位符(your_smtp_server,your_email@example.com,recipient@example.com)为你实际的SMTP服务器和邮箱信息。

此外,你可能需要更改smtp_port为你SMTP服务器使用的端口,通常为587(TLS/STARTTLS加密)或465(SSL加密)。

确保你的SMTP服务器支持你选择的端口和加密方式。在实际应用中,你还可能需要提供SMTP服务器的身份验证信息,包括用户名和密码。

这只是一个基本示例,实际情况可能需要更多的配置和错误处理。在生产环境中,确保保护敏感信息,如密码。


转载请注明出处:http://www.zyzy.cn/article/detail/6474/Ruby