Tarang
Tarang

Reputation: 75955

Mail gem determine whether plaintext or html

I'm using the mail gem from https://github.com/mikel/mail

I use it to parse raw mail data: e.g

require 'mail'

maildata = Mail.new(body) #where body is the raw text of an email message

#from there I can see info such as
p maildata.body.decoded #displays the decoded email body
p maildata.from #shows who the email is from

How would I figure out whether the email is plaintext or html is there a built in way to do this?

Upvotes: 2

Views: 496

Answers (2)

Artur INTECH
Artur INTECH

Reputation: 7376

mail = Mail.new do
  text_part do
    body 'test'
  end

  html_part do
    content_type 'text/html; charset=utf-8'
    body '<b>test</b>'
  end
end

mail.multipart? # true
puts mail.html_part.decoded # "<b>test</b>"
puts mail.text_part # "test"

Upvotes: 0

Dylan Markow
Dylan Markow

Reputation: 124449

You could look at maildata.content_type:

maildata.content_type
#=> "text/plain; charset=us-ascii"

If it's a multipart e-mail, you could have both plain text and HTML. You could then look at the parts array to see which content types it includes:

maildata.content_type
#=> "multipart/alternative; boundary=\"--==_mimepart_4f848491e618f_7e4b6c1f3849940\"; charset=utf-8"

maildata.parts.collect { |part| part.content_type }
#=> ["text/plain; charset=utf-8", "text/html; charset=utf-8"]

Upvotes: 2

Related Questions