bkaiser
bkaiser

Reputation: 657

How to send HTML content in email from net//smtp in ruby?

Pertinent code:

msg = "Subject: Reset password instructions\n\nHello " + @request_payload["email"] + "!\n\n" +
      "A new account has been created for you at <a href=\"presentation-layer.dev\">presentation-layer.dev<a>." + 
      "Please go to that page and click \"forgot password\" to set your password."
      smtp = Net::SMTP.new 'smtp.gmail.com', 587
      smtp.enable_starttls
      smtp.start('domain', "email", 'password', :login) do
        smtp.send_message(msg, 'sender', "recip")
      end

The resulting email just has the raw text in it. How do I get the server to evaluate the HTML tags?

Upvotes: 2

Views: 4168

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

To do what you want, you should generate a MIME document. If you really want to do it right, create a multipart MIME document so you have both the TEXT and rich-text parts.

You can do it from Net::SMTP, but you have to add the necessary MIME header and part dividers to the document. See "Sending Email using Ruby - SMTP" for an example how.

It's easier to use the Mail gem, which supports both, especially if you're including multiple parts or adding attachments. From the documentation:

You can also create MIME emails. There are helper methods for making a multipart/alternate email for text/plain and text/html (the most common pair) and you can manually create any other type of MIME email.

And farther down in the document in "Writing and sending a multipart/alternative (html and text) email":

Mail makes some basic assumptions and makes doing the common thing as simple as possible.... (asking a lot from a mail library)

mail = Mail.deliver do
  to      '[email protected]'
  from    'Mikel Lindsaar <[email protected]>'
  subject 'First multipart email sent with Mail'

  text_part do
      body 'This is plain text'
  end

  html_part do
      content_type 'text/html; charset=UTF-8'
      body '<h1>This is HTML</h1>'
  end
end

Upvotes: 5

Vlad the Impala
Vlad the Impala

Reputation: 15872

Sounds like you need to set the 'Content-Type' header:

Content-Type: text/html;

Upvotes: 0

Related Questions