Skip to content

Instantly share code, notes, and snippets.

@zealot128
Created May 20, 2012 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zealot128/2759376 to your computer and use it in GitHub Desktop.
Save zealot128/2759376 to your computer and use it in GitHub Desktop.
Imap mail statistic with Ruby
require "net/imap"
require "progressbar"
require "active_support/all" # sort_by!
class Array
def histogram ; self.sort.inject({}){|a,x|a[x]=a[x].to_i+1;a} ; end
end
server = "mailserver.com"
username = "mail@mailserver.com"
password = "password"
boxes = ["INBOX"] # list all the IMAP folders to include in the calculations
imap = Net::IMAP.new(server)
imap.login(username, password)
# loop through all boxes, adding all mail-ids to the list
mail_ids = boxes.inject([]) do |sum, box|
imap.select("INBOX")
sum += imap.search(["ALL"])
end
puts "Found #{mail_ids.count} Mails in Boxes #{boxes.join(", ")}. Now Fetching Mail Headers..."
# new progressbar
pbar = ProgressBar.new "mails:", mail_ids.count
most = mail_ids.map do |id|
pbar.inc
# the sender is somewhat deep inside the mail...
sender = imap.fetch(id, "ENVELOPE").first.attr["ENVELOPE"].sender.first
"#{sender.mailbox}@#{sender.host}"
end.histogram
pbar.finish
most = most.to_a.sort_by{|address,count| -count}
puts most.map{|address,count| "#{address}; #{count}"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment