Edmund Edmund - 18 days ago 6
Ruby Question

Ruby and sending emails with Net::SMTP: How to specify email subject?

I have a ruby app and I am sending emails with this format found in the documentation 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'

This is my code:

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.

Net::SMTP.start('localhost', 25) do |smtp|
smtp.send_message(msgstr, "exchangeerrors@5112.mysite.com", "emai@mysite.com")

However, the emails being sent have no subjects in them. The
just becomes the body of the email. I don't see anywhere in the documentation on how to specify a mail subject. Does anyone know?


So I looked at the documentation and it looks like Net::SMTP doesn't support this. In the documentation it says this:

What is This Library NOT?¶ ↑

This library does NOT provide functions to compose internet mails. You must create them by yourself. If you want better mail support, try RubyMail or TMail. You can get both libraries from RAA. (www.ruby-lang.org/en/raa.html)

So I looked into the MailFactory gem (http://mailfactory.rubyforge.org/), which uses Net::SMTP actually:

    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"

    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)

and now it works!