Mail gem - how to clean up the body string

回眸只為那壹抹淺笑 提交于 2019-12-04 09:29:32

问题


I'm trying to read an email using ruby mail gem. But mail.body.decoded returns me not just the body message. How can I clean up this body message and remove unwanted text like:

-20cf30433c9a437cc304939017ef\nContent-Type: text/plain; charset=ISO-8859-1\nContent-

message = $stdin.read
mail = Mail.read_from_string(message)
puts mail.body.decoded

--20cf30433c9a437cc304939017ef\nContent-Type: text/plain; charset=ISO-8859-1\nContent-Transfer-Encoding: quoted-printable\n\n REAL BODY TEXT \\n\n--20cf30433c9a437cc304939017ef\nContent-Type: text/html; charset=ISO-8859-1\nContent-Transfer-Encoding: quoted-printable\n\n<br clear=3D\"all\">--20cf30433c9a437cc304939017ef--

How can I clean up this email body mail message extracting only the REAL BODY TEXT , without ANY header ?

I'm creating a simple Ticket System based in Ruby on Rails, and a ticket is created when an email is received by ticket@mydomain.com. But when the message is in HTML format the BODY TEXT is surrounded by HEADERs text.


回答1:


If you have a properly formatted email, you can use Mail helper methods:

mail = Mail.new(email_string)
mail.text_part # finds the first text/plain part
mail.html_part # finds the first text/html part

This doesn't always work if you have e.g. single part messages (text only) or receive email from the internet at large since you can't rely on formatting from every client out there. Believe me, I've learned the hard way.




回答2:


looks like you've got a multipart email, so you can use mail.parts[0].body.decoded These will probably come in handy too: mail.multipart?
mail.parts.length

The gem documentation at github is pretty decent




回答3:


With the mail gem, you can do:

text = mail.multipart? ? mail.text_part.decoded : mail.body.decoded`



回答4:


Add the mail gem and just use email body format with mail.parts[1].body.decoded.



来源:https://stackoverflow.com/questions/4033376/mail-gem-how-to-clean-up-the-body-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!