自动收取邮件的python代码出错,求高手指教
我想用邮件写个自动收取邮件,然后自动下到本机的python代码,但是在写入文件的时候,老是自动报错,我要把报错的地方注释掉,就不能写内容。求教高手
# -*- coding: cp936 -*-import poplibimport cStringIOimport emailimport base64import ospop3_server = 'pop.163.com'user_name = 'XXXX@163.com'password = 'XXXX'#POP3取信M = poplib.POP3(pop3_server)M.user(user_name)M.pass_(password)#打印有多少封信numMessages = len(M.list()[1])print ('num of messages', numMessages) for i in range(numMessages): m = M.retr(i+1) buf = cStringIO.StringIO() for j in m[1]: print >> buf, j buf.seek(0)#解析信件内容 msg = email.message_from_file(buf) for part in msg.walk(): contenttype = part.get_content_type() filename = part.get_filename() if contenttype == 'application/octet-stream': if filename == None: continue # 保存附件 f = open( "mail%d_%s.attach" % (i+1,filename), 'wb') f.write(base64.decodestring(part.get_payload())) f.close() elif contenttype == 'text/plain': # 保存正文 f = open( "mail%d.eml " % (i+1), 'wb') f.write(base64.decodestring(part.get_payload())) f.close()
def processMsg(entire_msg): body = '' msg = email.message_from_string(entire_msg) if msg.is_multipart(): for part in msg.walk(): if part.get_content_type() == 'text/plain': body = part.get_payload() break else: body = msg.get_payload(decode=True) else: body = msg.get_payload(decode=True) return body