Ruby 简明教程
Sending Email using Ruby - SMTP
简单邮件传输协议 (SMTP) 是一种协议,处理在邮件服务器之间发送和路由电子邮件。
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers.
Ruby 提供 Net::SMTP 类用于简单邮件传输协议 (SMTP) 客户端连接,并提供了两个类方法 new 和 start。
Ruby provides Net::SMTP class for Simple Mail Transfer Protocol (SMTP) client-side connection and provides two class methods new and start.
-
The new takes two parameters − The server name defaulting to localhost. The port number defaulting to the well-known port 25.
-
The start method takes these parameters − The server − IP name of the SMTP server, defaulting to localhost. The port − Port number, defaulting to 25. The domain − Domain of the mail sender, defaulting to ENV["HOSTNAME"]. The account − Username, default is nil. The password − User password, defaulting to nil. The authtype − Authorization type, defaulting to cram_md5.
一个 SMTP 对象具有一个实例方法 sendmail,它通常用于发送邮件。它采用三个参数 -
An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message. It takes three parameters −
-
The source − A string or array or anything with an each iterator returning one string at a time.
-
The sender − A string that will appear in the from field of the email.
-
The recipients − A string or an array of strings representing the recipients' addressee(s).
Example
下面是使用 Ruby 脚本发送一封电子邮件的简单方法,试试吧 -
Here is a simple way to send one email using Ruby script. Try it once −
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
这里,你使用文档将基本电子邮件放入消息中,并注意正确设置标头格式。电子邮件需要一个 From 、 To 和 Subject 标头,并用空行与电子邮件正文分开。
Here, you have placed a basic e-mail in message, using a document, taking care to format the headers correctly. E-mails require a From, To, and Subject header, separated from the body of the e-mail with a blank line.
要发送邮件,你可以使用 Net::SMTP 连接到本地计算机上的 SMTP 服务器,然后将 send_message 方法与邮件、发件人地址和目标地址一起用作参数(尽管发件人和收件人地址都在电子邮件本身中,但这些地址并不总是用于路由邮件)。
To send the mail you use Net::SMTP to connect to the SMTP server on the local machine and then use the send_message method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren’t always used to route mail).
如果你不打算在计算机上运行 SMTP 服务器,你可以使用 Net::SMTP 与远程 SMTP 服务器进行通信。除非你正在使用 Web 邮件服务(例如 Hotmail 或 Yahoo! Mail),你的电子邮件提供商会向你提供发件服务器详细信息,你可以将其提供给 Net::SMTP,具体如下 -
If you’re not running an SMTP server on your machine, you can use the Net::SMTP to communicate with a remote SMTP server. Unless you’re using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider will have provided you with outgoing mail server details that you can supply to Net::SMTP, as follows −
Net::SMTP.start('mail.your-domain.com')
此代码行将连接到 mail.your-domain.com 的端口 25 上的 SMTP 服务器,而不会使用任何用户名或密码。不过,如果你需要,你可以指定端口号和其他详细信息。例如 -
This line of code connects to the SMTP server on port 25 of mail.your-domain.com without using any username or password. If you need to, though, you can specify port number and other details. For example −
Net::SMTP.start('mail.your-domain.com',
25,
'localhost',
'username', 'password' :plain)
此示例使用用户名和明文格式的密码连接到 mail.your-domain.com 上的 SMTP 服务器。它将客户端的主机名标识为 localhost。
This example connects to the SMTP server at mail.your-domain.com using a username and password in plain text format. It identifies the client’s hostname as localhost.
Sending an HTML e-mail using Ruby
如果你使用 Ruby 发送文本消息,那么所有内容都将被视为简单文本。即使你在文本消息中包含 HTML 标签,它也会显示为简单文本,HTML 标签不会根据 HTML 语法进行格式化。但是,Ruby Net::SMTP 提供了将 HTML 消息作为实际 HTML 消息发送的选项。
When you send a text message using Ruby then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Ruby Net::SMTP provides option to send an HTML message as actual HTML message.
发送邮件时,你可以指定一个 Mime 版本、内容类型和字符集来发送 HTML 邮件。
While sending an email message you can specify a Mime version, content type and character set to send an HTML email.
Example
以下是将 HTML 内容作为电子邮件发送的示例,试试吧 -
Following is the example to send HTML content as an email. Try it once −
require 'net/smtp'
message = <<MESSAGE_END
From: Private Person <me@fromdomain.com>
To: A Test User <test@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP e-mail test
This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
MESSAGE_END
Net::SMTP.start('localhost') do |smtp|
smtp.send_message message, 'me@fromdomain.com', 'test@todomain.com'
end
Sending Attachments as an e-mail
要发送包含混合内容的电子邮件,需要将 Content-type 标头设置为 multipart/mixed 。然后,可以在 boundaries 中指定文本和附件部分。
To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries.
一个边界的开头是两个连字符后跟一个唯一数字,它不能出现在电子邮件的消息部分。表示电子邮件的最终部分的最终边界也必须以两个连字符结束。
A boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the email. A final boundary denoting the email’s final section must also end with two hyphens.
附加文件应使用 pack("m") 函数进行编码,以便在传输之前进行 base64 编码。
Attached files should be encoded with the pack("m") function to have base64 encoding before transmission.
Example
以下是发送文件 /tmp/test.txt 作为附件的示例。
Following is the example, which will send a file /tmp/test.txt as an attachment.
require 'net/smtp'
filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
filecontent = File.read(filename)
encodedcontent = [filecontent].pack("m") # base64
marker = "AUNIQUEMARKER"
body = <<EOF
This is a test email to send an attachement.
EOF
# Define the main headers.
part1 = <<EOF
From: Private Person <me@fromdomain.net>
To: A Test User <test@todmain.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary = #{marker}
--#{marker}
EOF
# Define the message action
part2 = <<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit
#{body}
--#{marker}
EOF
# Define the attachment section
part3 = <<EOF
Content-Type: multipart/mixed; name = \"#{filename}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename = "#{filename}"
#{encodedcontent}
--#{marker}--
EOF
mailtext = part1 + part2 + part3
# Let's put our code in safe area
begin
Net::SMTP.start('localhost') do |smtp|
smtp.sendmail(mailtext, 'me@fromdomain.net', ['test@todmain.com'])
end
rescue Exception => e
print "Exception occured: " + e
end
NOTE − 您可以在数组内部指定多个目标,但是它们应该以逗号分隔。
NOTE − You can specify multiple destinations inside the array but they should be separated by comma.