Question

I'm facing trouble decoding messages fetched through ruby's Net::IMAP, here's what I've tried in console

imap = Net::IMAP.new(‘imap.gmail.com’,993,true)
imap.login(“my@gmail.com”, “mypassword”)
imap.select(‘INBOX’)

msgs = []

imap.uid_search(["NOT", "DELETED"]).each do |uid|
  msgs << imap.uid_fetch(uid, ['RFC822']).first.attr['RFC822'].to_s
end

Now when I'm doing msgs.first I'm getting this

"Return-Path: <my@gmail.com>\r\n
Received: from 192.168.10.191:3000 ([111.93.167.67])\r\n       
 by mx.google.com with ESMTPSA id kz4sm35619700pbc.39.1969.12.31.16.00.00\r\n 
(version=TLSv1.1 cipher=ECDHE-RSA-RC4-SHA bits=128/128);\r\n
Thu, 05 Sep 2013 06:18:24 -0700 (PDT)\r\n
Date: Thu, 05 Sep 2013 18:48:18 +0530\r\n
From: my@gmail.com\r\n
Reply-To: please-change-me-at-config-initializers-devise@example.com\r\n
To: admin@example.com\r\n
Message-ID: <5228849ab79c5_4b57133029c665c4@rajde1.mail>\r\n
Subject: Confirmation instructions\r\n
Mime-Version: 1.0\r\n
Content-Type: text/html;\r\n
charset=UTF-8\r\n
Content-Transfer-Encoding: 7bit\r\n\r\n
<p>Welcome admin@example.com!</p>\r\n\r\n<p>You can confirm your account email through the link below:</p>\r\n\r\n<p><a href=\"http://192.168.10.191:3000/users/confirmation?confirmation_token=jqFrp48CyqnFDwBKpxBV\">Confirm my account</a></p>\r\n"

How to decode this, please help. I'm new to this feature.

Was it helpful?

Solution

When you retrieve RFC822 you get the whole thing. If you retrieve BODY.PEEK[HEADER.FIELDS (Subject)] you'll get just the subject. (There's also an ENVELOPE which can be quite handy, it contains Subject, From and a few more, neatly parsed for you.) Fetching the body (I assume that's what you mean by content) is a little more tricky, you need to first retrieve the bodystructure, then retrieve the parts you want, often BODY.PEEK[1] or BODY.PEEK[1.2] or somesuch.

OTHER TIPS

Try using something like this:

body1 = imap.fetch(uid, "RFC822")[0].attr["RFC822"]
mail = Mail.new(body1)
subject = mail.subject
to      = mail.to

like that you could take all the value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top