如何使用ruby gmail gem提取邮件正文?

时间:2016-11-21 15:30:16

标签: ruby email

我正在使用ruby Gmail gem来阅读即将发送的电子邮件。我可以成功获取日期/主题/邮箱/主机,但我无法从email.body中提取电子邮件正文。基本上,我只希望看到"最后一个标题日期最后一次访问https://www.google.com"但是我正在吼叫。

def main
   gmail = Gmail.connect(USERNAME, PASSWORD)
   gmail.inbox.find(:unread).each do |email|
      puts email.body

   end
   gmail.logout
end

if __FILE__ == $PROGRAM_NAME
   main()
end

返回

--001a113d2dde4115020541d12a51
Content-Type: text/plain; charset=UTF-8

Last First
A Title
Date last accessed
https://www.google.com

--001a113d2dde4115020541d12a51
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<div dir=3D"ltr"><div><span style=3D"font-size:16px">Last First</span></div=
><div><span style=3D"font-size:16px">A Title</span></div><div><div style=3D=
"font-size:12.8px"><span style=3D"font-size:16px">Date last accessed</span>=
<span style=3D"font-size:16px"><br></span><div><a href=3D"https://www.googl=
e.com" target=3D"_blank">https://www.google.com</a></div></div></div><div><=
br><br></div></div>

--001a113d2dde4115020541d12a51--

1 个答案:

答案 0 :(得分:0)

Gmail gem使用Mail gem所以解决方案来自邮件gem / mail gem问题。我跟着=&gt; enter link description here

#!/usr/bin/ruby
require 'gmail'
USERNAME = 'xxxxxxx@gmail.com'
PASSWORD = 'xxxxxxxx'

def main
    gmail = Gmail.connect(USERNAME, PASSWORD)
    gmail.inbox.find(:unread).each do |email|
        puts email.text_part ? email.text_part.body.decoded : nil   
        #puts email.html_part ? email.html_part.body.decoded : nil
    end
    gmail.logout
end

if __FILE__ == $PROGRAM_NAME
    main()
end