jeton
jeton

Reputation: 921

How to extract email body using ruby gmail gem?

I am using ruby Gmail gem to read coming emails. I can successfully get date/subject/mailbox/host but I couldn't extract email body from email.body. Basically, I want to see only "Last First A Title Date last accessed https://www.google.com" but I am getting bellow.

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

It returns

--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--

Upvotes: 0

Views: 1530

Answers (1)

jeton
jeton

Reputation: 921

Gmail gem uses Mail gem so solution is coming from mail gem / mail gem questions. I follow => enter link description here

#!/usr/bin/ruby
require 'gmail'
USERNAME = '[email protected]'
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

Upvotes: 1

Related Questions