Ruby and sending emails with Net::SMTP: How to specify email subject?
我有一个ruby应用程序,我发送的文件http://ruby-doc.org/stdlib-2.0/libdoc/net/smtp/rdoc/Net/SMTP.html中提供了这种格式的电子邮件:
1 2 3 | Net::SMTP.start('your.smtp.server', 25) do |smtp| smtp.send_message msgstr, 'from@address', 'to@address' end |
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def send_notification(exception) msgstr = <<-END_OF_MESSAGE From: Exchange Errors <exchangeerrors@5112.mysite.com> To: Edmund Mai Subject: test message Date: Sat, 23 Jun 2001 16:26:43 +0900 Message-Id: <unique.message.id.string@mysite.com> This is a test message. END_OF_MESSAGE Net::SMTP.start('localhost', 25) do |smtp| smtp.send_message(msgstr,"[email protected]","[email protected]") end end |
但是,发送的电子邮件中没有主题。
所以我看了一下文档,看起来Net :: SMTP不支持这个。在文档中它说:
什么是这个图书馆? ↑
该库不提供撰写互联网邮件的功能。你必须自己创建它们。如果您想获得更好的邮件支持,请尝试使用RubyMail或TMail。您可以从RAA获取这两个库。 (www.ruby-lang.org/en/raa.html)
所以我查看了MailFactory gem(http://mailfactory.rubyforge.org/),它实际上使用了Net :: SMTP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | require 'net/smtp' require 'rubygems' require 'mailfactory' mail = MailFactory.new() mail.to ="[email protected]" mail.from ="[email protected]" mail.subject ="Here are some files for you!" mail.text ="This is what people with plain text mail readers will see" mail.html ="A little something special for people with HTML readers" mail.attach("/etc/fstab") mail.attach("/some/other/file") Net::SMTP.start('smtp1.testmailer.com', 25, 'mail.from.domain', fromaddress, password, :cram_md5) { |smtp| mail.to = toaddress smtp.send_message(mail.to_s(), fromaddress, toaddress) } |
现在它有效!
我实际上设法用一个主题发送带有NET :: SMTP的邮件,我认为缩进很重要(例子来自http://www.tutorialspoint.com/ruby/ruby_sending_email.htm) -
1 2 3 4 5 6 7 8 9 10 11 | message = <<MESSAGE_END From: Private Person <[email protected]> To: A Test User <[email protected]> Subject: SMTP e-mail test This is a test e-mail message. MESSAGE_END Net::SMTP.start('localhost') do |smtp| smtp.send_message message, '[email protected]', '[email protected]' end |
主题是正确的。如果您打印变量"message",您将获得此输出 -
1 2 3 4 5 6 | "From: Private Person <[email protected]> To: A Test User <[email protected]> Subject: SMTP e-mail test This is a test e-mail message. " |
虽然这段代码在"主题"前面有空格 -
1 2 3 4 5 6 7 8 9 10 11 | message = <<MESSAGE_END From: Private Person <[email protected]> To: A Test User <[email protected]> Subject: SMTP e-mail test This is a test e-mail message. MESSAGE_END Net::SMTP.start('localhost') do |smtp| smtp.send_message message, '[email protected]', '[email protected]' end |
将打印 -
1 2 3 4 5 6 | "From: Private Person <[email protected]> To: A Test User <[email protected]> Subject: SMTP e-mail test This is a test e-mail message. " |
然后主题将无法正常工作。
我知道这现在几乎没用了但是,我尝试使用Net :: SMTP发送电子邮件,并且能够设置主题。也许你可以尝试过