Search code examples
htmlrubyemailmime-types

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            => 'myname@domain.com',
                       :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    'myname@domain.com'
            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.


Solution

  • 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      'nicolas@test.lindsaar.net.au'
      from    'Mikel Lindsaar <mikel@test.lindsaar.net.au>'
      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