返回邮件的主题还有发件人
from email import *
import re,email,email.header
from poplib import POP3
def decode_email_content(msg_src,names):
msg=email.message_from_string(msg_src)#email.message_from_bytes只可以在python 3中运行
#print msg
result = { }
for name in names:
content = msg.get(name)
#print content
info = email.header.decode_header(content)#解码
print info
if info[0][1]:
print '^^^^^'
if info[0][1].find('unknown-') ==-1:#已知编码
result[name] = info[0][0].decode(info[0][1])
else:#未知编码
try:
result[name] = info[0][0].decode('gbk')
except:
result[name] = info[0][0].decode('utf-8')
else:
result[name] = info[0][0]
return result
if __name__== "__main__":
pp=POP3("pop3.163.com")
pp.user('*******@163.com')
pp.pass_('*******')
total,totalnum = pp.stat()#邮件的数量和邮件总的字节数
print (total,totalnum)
for i in range(total-2,total):
hinfo,msgs,octet=pp.top(i+1,0)#得到指定邮件中的第一行内容(从0开始)
# print'%%%%%%'
# print hinfo
# print'%%%%%'
# print msgs
# print'&&&&'
# print octet
b=b''
for msg in msgs:
b += msg+b'\n'
items = decode_email_content(b,['subject','from'])
print items['subject'],'\nFrom:',items['from']
pp.quit()