Ruby 发送邮件 - SMTP
Ruby 发送邮件 - SMTP
本文将介绍如何使用 Ruby 中的 SMTP 模块发送邮件。
SMTP 模块
SMTP 是一种用于发送电子邮件的协议,而 Ruby 的 SMTP 模块是一个封装了 SMTP 协议的类库,它允许您使用 Ruby 代码通过电子邮件发送消息。
邮箱配置
在使用 SMTP 模块发送邮件之前,您需要获取您的邮箱的 SMTP 服务器地址、端口、用户名和密码。以下是几个常见邮箱提供商的 SMTP 服务器信息:
- Gmail:smtp.gmail.com,端口 587,需要启用 TLS 加密。
- Outlook.com:smtp.live.com,端口 587,需要启用 TLS 加密。
- Yahoo:smtp.mail.yahoo.com,端口 465 或 587,需要启用 SSL 加密。
发送邮件
下面是使用 SMTP 模块发送邮件的基本代码:
require 'net/smtp'
message = <<END_OF_MESSAGE
From: Your Name <your_email@example.com>
To: Destination Address <destination_email@example.com>
Subject: Your Subject
Date: #{Time.now.rfc2822}
Your message goes here.
END_OF_MESSAGE
smtp = Net::SMTP.new 'smtp.gmail.com', 587
smtp.enable_starttls
smtp.start('example.com', 'username', 'password', :login) do
smtp.send_message message, 'your_email@example.com', 'destination_email@example.com'
end
在此示例中,我们首先定义了一个消息,该消息包含邮件的主要元素,例如发件人、收件人、主题和正文。接下来,我们创建一个 Net::SMTP 实例并将其配置为使用 Gmail 的 SMTP 服务器,并通过启用 TLS 加密来保护连接。然后我们使用 start 方法建立一个会话,该方法需要传递 SMTP 服务器地址、用户名,密码以及身份验证方式参数。在会话建立后,我们使用 send_message 方法发送邮件。
发送附件
SMTP 模块也支持在邮件中添加附件。以下代码演示了如何在邮件中添加单个附件:
require 'net/smtp'
require 'mail'
message = Mail.new do
from 'Your Name <your_email@example.com>'
to 'Destination Address <destination_email@example.com>'
subject 'Your Subject'
body 'Your message goes here.'
add_file '/path/to/attachment.pdf'
end
smtp = Net::SMTP.new 'smtp.gmail.com', 587
smtp.enable_starttls
smtp.start('example.com', 'username', 'password', :login) do
smtp.send_message message.to_s, 'your_email@example.com', 'destination_email@example.com'
end
在此示例中,我们使用 Mail 库创建一个 Mail 对象,并使用 add_file 方法添加一个名为 “attachment.pdf” 的附件。
结论
通过使用 Ruby 的 SMTP 模块,您可以轻松地从您的 Ruby 应用程序中发送电子邮件。在此文档中,我们介绍了如何配置电子邮件信息并使用 SMTP 模块发送电子邮件,以及如何添加附件。记得始终遵循最佳实践和安全措施,特别是在涉及电子邮件的敏感数据和信息时。