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

big*_*ato 4 ruby email

我有一个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
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

def send_notification(exception)

    msgstr = <<-END_OF_MESSAGE
        From: Exchange Errors <exchangeerrors@5112.mysite.com>
        To: Edmund Mai <emai@mysite.com>
        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, "exchangeerrors@5112.mysite.com", "emai@mysite.com")
    end
end
Run Code Online (Sandbox Code Playgroud)

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

big*_*ato 7

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

这个图书馆不是什么?↑

该库不提供撰写互联网邮件的功能.你必须自己创建它们.如果您想获得更好的邮件支持,请尝试使用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 <b>special</b> 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)
    }
Run Code Online (Sandbox Code Playgroud)

现在它有效!