开发者

How to get the recipient address of an email via IMAP in Ruby

We have a user whose mail account is deluged with spam. I'm suspecting that he fields a large number of email accounts and therefore is subject to more than he might be with only one or two addresses.

I want to knock up some code 开发者_如何学编程which will scan his mailbox and report on the number of addresses that were mailed to (ideally the ones which delivered to his mailbox, eg if he's BCC'd and the To: is billg@microsoft.com, I'd like to know which address was the one which reached him).

I can get the To: if it's present in the envelope, but if not then I need to fall back on alternatives like Cc: and maybe actually get regex-y in the message headers to ID who this message was delivered for. I can handle that. I'm just not sure about how to pull apart the Ruby msg object.

So maybe a better question for me would be, "knowing that I have an object msg returned from imap.fetch, how may I inspect the various methods available such as msg.to and msg.from?"

And perhaps also "should I be using a fancy mail library like Ruby's Mail?"

Code so far - I'm REALLY new to Ruby, OK?

imap = Net::IMAP.new(server)
imap.login(user, pass)
imap.select(folder)

imap.search(['ALL']).each do |message_id|
  msg = imap.fetch(message_id,'ENVELOPE')[0].attr['ENVELOPE']
  if msg.to
    puts "#{msg.to[0].mailbox}@#{msg.to[0].host}: \t#{msg.from[0].name}: \t#{msg.subject}"
  else 
#    puts msg.inspect
    msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
    puts msg.inspect
    quit
  end
#   p msg.methods
end


I do something similar to this for a script that I have. It might help you out. The key to remember is that all elements returned are arrays, even if they only have 1 element.

imap.search(["ALL"]).each do |msg|
  envelope = imap.fetch(msg, "ENVELOPE")[0].attr["ENVELOPE"]
  sender = envelope.from[0].mailbox # This will give you the mailbox name without @domain.com
  recipient = envelope.to[0].mailbox # You can also do envelope.to.each { operations } to get the full list of recipients
end

The envelope is what contains all of the data you are trying to look at.

envelope.from[0].mailbox is the sender without the @domain.com

envelope.to[0] is the first recipient without the @domain.com

envelope.subject is the subject

and so on and so on

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜