Ruby 发送邮件 - SMATP

SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。

Ruby提供了 Net::SMTP 来发送邮件,并提供了两个方法 new 和 start:

new 方法有两个参数:

  • server name 默认为 localhost
  • port number 默认为 25

start 方法有以下参数:

  • server - SMTP 服务器 IP, 默认为 localhost
  • port - 端口号,默认为 25
  • domain - 邮件发送者域名,默认为 ENV["HOSTNAME"]
  • account - 用户名,默认为 nil
  • password - 用户密码,默认为nil
  • authtype - 验证类型,默认为 cram_md5

SMTP 对象实例化方法调用了 sendmail, 参数如下:

  • source - 一个字符串或数组或每个迭代器在任一时间中返回的任何东西。
  • sender -一个字符串,出现在 email 的表单字段。
  • recipients - 一个字符串或字符串数组,表示收件人的地址。

实例

以下提供了简单的Ruby脚本来发送邮件:

实例

require 'net/smtp' message = <<MESSAGE_END From: Private Person <me@fromdomain.com> To: A Test User <test@todomain.com> Subject: SMTP e-mail test This is a test e-mail message. MESSAGE_END Net::SMTP.start('localhost') do |smtp| smtp.send_message message, 'me@fromdomain.com', 'test@todomain.com' end