Rails - Mail, getting the body as Plain Text

AnApprentice picture AnApprentice · Feb 1, 2011 · Viewed 26.6k times · Source

Given: message = Mail.new(params[:message])

as seen here: http://docs.heroku.com/cloudmailin

It shows how to get the message.body as HTML, how to do you get the plain/text version?

Thanks

Answer

Steve Smith picture Steve Smith · Feb 1, 2011

The code above:

message = Mail.new(params[:message])

will create a new instance of the mail gem from the full message. You can then use any of the methods on that message to get the content. You can therefore get the plain content using:

message.text_part

or the HTML with

message.html_part

These methods will just guess and find the first part in a multipart message of either text/plain or text/html content type. CloudMailin also provides these as convenience methods however via params[:plain] and params[:html]. It's worth remembering that the message is never guaranteed to have a plain or html part. It may be worth using something like the following to be sure:

plain_part = message.multipart? ? (message.text_part ? message.text_part.body.decoded : nil) : message.body.decoded
html_part = message.html_part ? message.html_part.body.decoded : nil

As a side note it's also important to extract the content encoding from the message when you use these methods and make sure that the output is encoded into the encoding method you desire (such as UTF-8).