如何使用ruby的net/imap库读取电子邮件的正文? [英] How to read the body text of an email using ruby's net/imap library?

查看:62
本文介绍了如何使用ruby的net/imap库读取电子邮件的正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我今天脑子不好,但是我突然不知道怎么用ruby的net/imap库阅读电子邮件.我已经呆了几个小时了.我在Google中输入了"ruby​​ imap read body"的几种变体,并浏览了许多网站.它们全部都有有关如何提取附件,同步电子邮件服务器,使用gmail等的示例.有些(例如chilkat)实际上是共享软件库,可以为您完成此任务.我看过net/imap文档,尽管有几个示例可以用来完成除阅读正文之外的所有操作.

Maybe i've just got a bad brain today, but i suddenly can't figure out how to read an email with ruby's net/imap library. I've been at it for several hours. I typed several variations of "ruby imap read body" into google and have explored many sites. All of them have examples on how to pull attachments, sync e-mail servers, work with gmail etc... Some (like chilkat) are actually shareware libraries that do this for you. I have looked at the net/imap documentation and though there are several examples for doing everything but reading the body text.

我以前使用过net/imap,但只需要将收件箱中的附件下拉到目录中即可.我要求#ruby和#rubyonrails无济于事-没有人能弄清楚.

I've worked with net/imap before but i've only needed to pull down the attachments in an inbox to a directory. I've asked in #ruby and #rubyonrails to no avail - no one could figure it out.



imap=Net::IMAP.new('mail.xks.com') #of course these are not real
imap.login('web1_xk3','pxx2006')
imap.select('INBOX')
imap.search(["SENTSINCE",(Time.now-1.day).strftime("%d-%b-%Y")]).each do |msgid|
     body = imap.fetch(msgid,"BODY")[0].attr["BODY"]
     ##insert code for getting the text from the body here
     ##body.class is BodyTypeText 
end

P.S.尽管我在代码中确实提到了主动支持,但这是sans-rails,所以这意味着没有行动邮件发件人

P.S. Though I do make a reference to active support in the code, this is sans-rails so that means no action-mailer

推荐答案

如果只需要消息的正文内容,则可以使用:

If you just want just the body content of the message you can use:

body = imap.fetch(message_id,'BODY[TEXT]')[0].attr['BODY[TEXT]']

IMAP API有点深奥.如果您想处理整个邮件,建议您使用 TMail 将其解析为更易于使用的格式:

The IMAP API is a bit esoteric though. If you want to deal with the whole message, I would recommend using TMail to parse it into an easier to use format:

msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
mail = TMail::Mail.parse(msg)
body = mail.body

这篇关于如何使用ruby的net/imap库读取电子邮件的正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆