3
votes

I am using IMAP to receive some emails from gmail and then parse them with the new Rails 3 ActionMailer receive method.

raw_email   = imap.uid_fetch(uid, ['RFC822']).first.attr['RFC822']
email = UserMailer.receive(raw_email)

email is now a Mail::Message Class and to:, :from and :subject works fine. However I can't figure out how to get the plain text from the body. Before Rails 3 I could use the tmail_body_extractors plugin to get the plain body.

How would you do this with Rails 3?

Jakobinsky: email.body.raw_source is a bit closer be still gives me a lot of garbage.

"--001636310325efcc88049508323d\r\nContent-Type: text/plain; charset=ISO-8859-1\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\nThis is some body content\r\n\r\n--=20\r\nVenlig Hilsen\r\nAsbj=F8rn Morell\r\n\r\n--001636310325efcc88049508323d\r\nContent-Type: text/html; charset=ISO-8859-1\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\naf mail
--
Venlig Hilsen
Asbj=F8rn Morell
\r\n\r\n--001636310325efcc88049508323d--"

Should I roll my own helpers for cleaning up the raw_source or is there already a method ,gem or helper for that?

3

3 Answers

5
votes

See the answer on this question: Rails - Mail, getting the body as Plain Text

In short the solution is:

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

But I recommend reading the full answer as it is very good and comprehensive.

1
votes

You can extract the plain body from body.parts. There is still however some headers left in the body:

if body.multipart?
  body.parts.each do |p|
    if p.mime_type == "text/plain"
      body = p.body
    end
  end
end
body.to_s
0
votes

You should be able to retrieve the body as simple as email.body.raw_source. I haven't tested it myself, but you can take a look as the source code for ActionMailer:: Message#body.