简体   繁体   中英

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.

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM