ruby-on-railsrubyimapmultipart

How to display email body from email with Net::IMAP and Mail in Rails


I saw a bunch of other questions regarding this issue but most of them are either outdated or don't meet the same case as my problem.

So here is the issue. I fetch an email with Net::IMAP library and then create an Mail object from it so it is more readable.

# @imap is instance of Net::IMAP
mail = @imap.fetch(seqno, "RFC822")[0]
mail = Mail.read_from_string(mail.attr["RFC822"])

And then from that Mail object I can get this:

mail.body.to_s

And I will get the message, but before the message there will be a string looking kind of like this:

Content-Type: text/plain;\r\n charset=utf-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n

I just want to display the pure message to the user. Do you know any good parsers that can do this that are well documented with some examples?

Or is there any other better practice way to display emails?


Solution

  • Just after I posted this question I found the following solution.

    mail.html_part.body.decoded
    # or
    mail.text_part.body.decoded
    

    And then you check which one you want to display.