4

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?

kobaltz
  • 6,980
  • 1
  • 35
  • 52
atmorell
  • 3,052
  • 6
  • 30
  • 44

3 Answers3

5

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.

Community
  • 1
  • 1
arikfr
  • 3,311
  • 1
  • 25
  • 28
1

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
anajavi
  • 41
  • 1
  • 6
0

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.

Jakobinsky
  • 1,294
  • 8
  • 11
  • There is no gem to fetch/clean an email body as far as I know. However you should be able to use some regex in order to clean this output. – Jakobinsky Nov 15 '10 at 09:26
  • I down voted this answer because it doesn't give the correct answer and actually confuses. `email.body.raw_source` returns the body with the MIME type headers, which can be avoided without any special "cleaning" required. – arikfr Jun 20 '11 at 11:42