37,741
社区成员
发帖
与我相关
我的任务
分享
# -*- coding: cp936 -*-
import poplib
import cStringIO
import email
import base64
import os
pop3_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