fartagaintuxedo
fartagaintuxedo

Reputation: 749

How to setup send HTML email with mail gem?

I am sending email using the Mail gem. Here's my code:

require 'mail'
require 'net/smtp'

Mail.defaults do

delivery_method :smtp, { :address              => "smtp.arrakis.es",
                       :port                 => 587,
                       :domain               => 'webmail.arrakis.com',
                       :user_name            => '[email protected]',
                       :password             => 'pass',
                       :authentication       => 'plain',
                       :enable_starttls_auto => true  }

end

Mail::ContentTypeField.new("text/html") #this doesnt work

msgstr= File.read('text2.txt')

list.each do |entity|
    begin
        Mail.deliver do
            from    '[email protected]'
            to      "#{entity}"
            subject 'a good subject'
            body   msgstr
        end
    rescue => e
    end

end
end

I don't know how to set up the content type, so that I can format my email as html for example. Though I actually just wish to be able to define bold text like my email client does: bold text. Does anybody know which content-type I need to specify in order to achieve this, and how to implement it with mail?

Just a note, the code above works fine for sending plain text email.

Upvotes: 5

Views: 7702

Answers (2)

pjd
pjd

Reputation: 1173

@Simone Carletti's answer is essentially correct, but I was struggling with this and didn't want a plain text portion to my email and a separate HTML portion. If you just want the entire email to be HTML, something like this will work:

mail = Mail.deliver do
  to      '[email protected]'
  from    'Mikel Lindsaar <[email protected]>'
  subject 'First email sent with Mail'
  content_type 'text/html; charset=UTF-8'
  body '<h1>This is HTML</h1>'
end

I may have missed it, I didn't see anything in the Mail gem documentation describing how to do that, which I would think would be more common than making a multipart message. The documentation only seems to cover plain text messages and multipart messages.

Upvotes: 4

Simone Carletti
Simone Carletti

Reputation: 176412

From the documentation

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: 13

Related Questions