Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

email

ruby

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'
end

This is my code:

def send_notification(exception)

    msgstr = <<-END_OF_MESSAGE
        From: Exchange Errors <[email protected]>
        To: Edmund Mai <[email protected]>
        Subject: test message
        Date: Sat, 23 Jun 2001 16:26:43 +0900
        Message-Id: <[email protected]>

        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

However, the emails being sent have no subjects in them. The msgstr 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?

like image 843
bigpotato Avatar asked Jan 13 '23 05:01

bigpotato


1 Answers

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 = "[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 <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)
    }

and now it works!

like image 183
bigpotato Avatar answered Jan 14 '23 18:01

bigpotato