Ruby和使用Net :: SMTP发送电子邮件:如何指定电子邮件主题?

我有一个ruby应用程序,我发送文件http://ruby-doc.org/stdlib-2.0/libdoc/net/smtp/rdoc/Net/SMTP.html中的这种格式的电子邮件:

Net::SMTP.start('your.smtp.server', 25) do |smtp| smtp.send_message msgstr, 'from@address', 'to@address' end 

这是我的代码:

 def send_notification(exception) msgstr = <<-END_OF_MESSAGE From: Exchange Errors  To: Edmund Mai  Subject: test message Date: Sat, 23 Jun 2001 16:26:43 +0900 Message-Id:  This is a test message. END_OF_MESSAGE Net::SMTP.start('localhost', 25) do |smtp| smtp.send_message(msgstr, "exchangeerrors@5112.mysite.com", "emai@mysite.com") end end 

但是,发送的电子邮件中没有主题。 msgstr刚刚成为电子邮件的正文。 我没有在文档中看到有关如何指定邮件主题的任何内容。 有人知道吗?

所以我看了一下文档,看起来Net :: SMTP不支持这个。 在文档中它说:

这个图书馆不是什么?¶↑

该库不提供撰写互联网邮件的function。 你必须自己创建它们。 如果您想获得更好的邮件支持,请尝试使用RubyMail或TMail。 您可以从RAA获取这两个库。 (www.ruby-lang.org/en/raa.html)

所以我查看了MailFactory gem( http://mailfactory.rubyforge.org/ ),它实际上使用了Net :: SMTP:

  require 'net/smtp' require 'rubygems' require 'mailfactory' mail = MailFactory.new() mail.to = "test@test.com" mail.from = "sender@sender.com" 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发送电子邮件,并且能够设置主题。 也许你可以尝试过

Subject: 'test message'而不是Subject: test message

我实际上设法用一个主题发送带有NET :: SMTP的邮件,我认为缩进很重要(例子来自http://www.tutorialspoint.com/ruby/ruby_sending_email.htm ) –

 message = < To: A Test User  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 

主题是正确的。 如果您打印变量“message”,您将获得此输出 –

 "From: Private Person \nTo: A Test User \nSubject: SMTP e-mail test\n\nThis is a test e-mail message.\n" 

虽然这段代码在“主题”前面有空格 –

 message = < To: A Test User  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: Private Person \nTo: A Test User \n Subject: SMTP e-mail test\n\nThis is a test e-mail message.\n" 

然后主题将无法正常工作。