取pop3伺服器的郵件,分析出郵件標題,to cc bc from ,並保成為 .eml 檔案
1 import poplib 2 import StringIO, email 3 4 def dcode(str): 5 h = email.Header.Header(str) 6 dh = email.Header.decode_header(h) 7 return dh[0][0] 8 9 popsrv = "pop.xxxxxxxx.com" #串連 登入 伺服器 10 username = "hsbk@xxxxxx.com" 11 passwd = "123456" 12 13 14 subject="" 15 f_addr="" 16 f_name="" 17 to=[] 18 cc=[] 19 bc=[] 20 21 pop = poplib.POP3(popsrv) 22 #pop.set_debuglevel(1) 23 pop.user(username) 24 pop.pass_(passwd) 25 26 27 num,total_size = pop.stat() 28 hdr,text,octet=pop.retr(num) #取最後封郵件 29 text = '\n'.join(text) #將list拼接成字串 30 31 amail = email.message_from_string(text) 32 subject = dcode(amail.get("subject")) 33 34 35 36 f_addr = email.utils.parseaddr(amail.get("from"))[1] 37 f_name = dcode(email.utils.parseaddr(amail.get("from"))[0]) 38 39 40 41 42 tol=[] 43 tostr = msg.get('to') 44 45 if tostr == None : 46 tostr = '' 47 48 tostr = tostr.replace('\n','').replace('\t','').replace('"','').replace("'","") 49 tol = tostr.split(',') 50 for t in tol: 51 taddr = email.utils.parseaddr(t)[1] 52 inx = taddr.find("@") 53 if inx != -1: 54 to.append(taddr) 55 56 57 tol=[] 58 59 tostr = msg.get('bc') 60 61 if tostr == None : 62 tostr = '' 63 64 tostr = tostr.replace('\n','').replace('\t','').replace('"','').replace("'","") 65 66 tol = tostr.split(',') 67 for t in tol: 68 taddr = email.utils.parseaddr(t)[1] 69 inx = taddr.find("@") 70 if inx != -1: 71 bc.append(taddr) 72 73 74 tol=[] 75 tostr = msg.get('cc') 76 77 if tostr == None : 78 tostr = '' 79 80 tostr = tostr.replace('\n','').replace('\t','').replace('"','').replace("'","") 81 tol = tostr.split(',') 82 for t in tol: 83 taddr = email.utils.parseaddr(t)[1] 84 inx = taddr.find("@") 85 if inx != -1: 86 cc.append(taddr) 87 88 89 90 fp = open('e:/test3.eml','wb') 91 fp.write(text) 92 fp.close() 93 #pop.dele(num) #刪除伺服器上的副本 94 95 96 print "subject ",subject 97 print "f_addr ",f_addr 98 print "f_name ",f_name 99 print "to ",to100 print "cc ",cc101 print "bc ",bc102 103 104