简单邮件传输协议(SMTP)是一种协议,用于处理在邮件服务器之间发送电子邮件和路由电子邮件。
这是使用Ruby脚本发送一封电子邮件的简单方法。尝试一次-
链接:https://www.learnfk.comhttps://www.learnfk.com/ruby/ruby-sending-email.html
来源:LearnFk无涯教程网
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 标头,该标头与电子邮件正文之间用空白行分隔。
要发送邮件,请使用Net::SMTP连接到本地计算机上的SMTP服务器,然后使用send_message方法以及消息,发件人地址和目标地址作为参数。
如果您不在计算机上运行SMTP服务器,则可以使用Net::SMTP与RemoteSMTP服务器通信。除非您使用Webmail服务(如QQ或网易邮箱),否则您的电子邮件提供商将向您提供可以提供给Net::SMTP的外发邮件服务器详细信息,如下所示-
Net::SMTP.start('mail.your-domain.com')
此行代码使用任何用户名或密码连接到mail.your-domain.com端口25上的SMTP服务器。但是,如果需要,您可以指定端口号和其他详细信息。如-
Net::SMTP.start('mail.your-domain.com', 25, 'localhost', 'username', 'password' :plain)
本示例使用纯文本格式的用户名和密码连接到mail.your-domain.com上的SMTP服务器。
当您使用Ruby发送文本消息时,所有内容都将被视为简单文本。即使您将HTML标签包含在文本消息中,它也将显示为简单文本,并且不会根据HTML语法设置HTML标签的格式。但是Ruby Net::SMTP提供了将HTML消息作为实际HTML消息发送的选项。
发送电子邮件时,您可以指定Mime版本,内容类型和字符集来发送HTML电子邮件。
以下是将HTML内容作为电子邮件发送的示例。尝试一次-
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
要发送包含混合内容的电子邮件,需要将 Content-type 标头设置为 multipart/mixed 。然后可以在边界内指定文本和附件部分。
附件应在传输前使用 pack(" m")函数进行编码,以具有base64编码。
以下是示例,该示例将发送文件 /tmp/test.txt 作为附件。
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
注意-您可以在数组内指定多个目标,但它们之间应用逗号分隔。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)