import getpass, poplib, string, sys
import re

################

def check_re(d, patt_re, patt,  s):
    mo = patt_re.search(s)
    if mo:
        d[patt] = s
    return d

################

M = poplib.POP3(sys.argv[1])
##M.set_debuglevel(2)
M.user(sys.argv[2])
M.pass_(sys.argv[3])
###M.pass_(getpass.getpass())
from_pattern = re.compile("^from\:")
subj_pattern = re.compile("^subject\:")
date_pattern = re.compile("^date\:")
msft1_pattern = re.compile("^content-disposition: attachment; filename=")
haggis_pattern = re.compile("\@haggis")
w = M.list()
print w[0]
print w[1]
print w[2]
size_array = w[1]
numMessages = len(size_array)
print 'Num emails ', numMessages
for i in range(1, numMessages+1):
    d = {'from': '', 'subj': '', 'date': '', 'attach': '', 'haggis': ''}
    b = ['==============================================', '==============================================']
    x = M.top(i, 20)
    a = string.split(size_array[i-1], ' ')
    ndx = int(a[0])
    bcnt = int(a[1])
    #if bcnt > 10000:
    if bcnt > 1:
        b.append(('%d   %d' % (ndx, bcnt)))
        for y in x[1]:
            y1 = y.lower()
            d = check_re(d, from_pattern, 'from', y1)
            d = check_re(d, subj_pattern, 'subj', y1)
            d = check_re(d, date_pattern, 'date', y1)
            d = check_re(d, msft1_pattern, 'attach', y1)
            d = check_re(d, haggis_pattern, 'haggis', y1)
        for c in b:
            print c
        print d['from']
        print d['subj']
        print d['date']
        print d['attach']
        if (bcnt > 100000) and (d['haggis'] != ''):
            print '         TOO BIG!!!!!!!!!!!!!!!!!'
    
M.quit()

print '============================================================'
print '============================================================'
print '============================================================'
print '============================================================'
