def SaveAttach():# login the pop3 server ,retrive the new mails ,and download the attachments dstdir =dirname+str(time.ctime(time.time()))+'.zip' print 'starts' pp = poplib.POP3_SSL(mail_host,mail_port) print 'connect successful' pp.set_debuglevel(1) pp.user(mail_user) pp.pass_(mail_pass) ##list total count num = len(pp.list()[1]) print 'num of messages', num for i in range(1,num): #m = M.retr(i+1) m = pp.retr(i) buf = cStringIO.StringIO() buf.seek(0) msg = email.message_from_file(buf) for par in msg.walk(): #if not par.is_multipart(): name = par.get_filename() if name: print 'name',name data = par.get_payload(decode=True) try: f = open(dstdir, 'wb') #注意一定要用wb来打开文件,因为附件一般都是二进制文件 print 'save attfile succeed' except: print 'open file name error' f.write(data) f.close() pp.dele(i) else: #不是附件,是文本内容 body = par.get_payload(decode=True) # 解码出文本内容,直接输出来就可以了。 #print 'body:',body pass #print 'body:',body #中文没有处理好,所有没有输出了。 #print '+'*60 # 用来区别各个部分的输出 else: continue pp.quit() print 'exit'