tags:

views:

259

answers:

1

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 [email protected], 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
+2  A: 

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

Eugene
Thanks. I'm still trying to see how to reliably see what address this mail was sent to (ie, in the case of BCC or messages automatically forwarded/aliased from one address to another), for which I need to pull the headers apart more; the Envelope doesn't seem to contain that. I did discover headers = imap.fetch(message_id, 'RFC822.HEADER')[0].attr['RFC822.HEADER']which seems to be helpful.
Chris Burgess