Python实现读取邮箱中的邮件功能示例【含文本及附件】
本文实例讲述了Python实现读取邮箱中的邮件功能。分享给大家供大家参考,具体如下:
#-*-encoding:utf-8-*-
importsys
importlocale
importpoplib
fromemailimportparser
importemail
importstring
#确定运行环境的encoding
__g_codeset=sys.getdefaultencoding()
if"ascii"==__g_codeset:
__g_codeset=locale.getdefaultlocale()[1]
#
defobject2double(obj):
if(obj==Noneorobj==""):
return0
else:
returnfloat(obj)
#endif
#
defutf8_to_mbs(s):
returns.decode("utf-8").encode(__g_codeset)
#
defmbs_to_utf8(s):
returns.decode(__g_codeset).encode("utf-8")
#
host='pop.exmail.qq.com'
username='user1@xxxx.cn'
password='password'
pop_conn=poplib.POP3_SSL(host)
pop_conn.user(username)
pop_conn.pass_(password)
#Getmessagesfromserver:
#获得邮件
messages=[pop_conn.retr(i)foriinrange(1,len(pop_conn.list()[1])+1)]
#printmessages
#print"--------------------------------------------------"
#Concatmessagepieces:
messages=["\n".join(mssg[1])formssginmessages]
#printmessages
#Parsemessageintomanemailobject:
#分析
messages=[parser.Parser().parsestr(mssg)formssginmessages]
i=0
forindexinrange(0,len(messages)):
message=messages[index];
i=i+1;
subject=message.get('subject')
h=email.Header.Header(subject)
dh=email.Header.decode_header(h)
subject=unicode(dh[0][0],dh[0][1]).encode('utf8')
mailName="mail%d.%s"%(i,subject)
f=open('%d.log'%(i),'w');
print>>f,"Date:",message["Date"]
print>>f,"From:",email.utils.parseaddr(message.get('from'))[1]
print>>f,"To:",email.utils.parseaddr(message.get('to'))[1]
print>>f,"Subject:",subject
print>>f,"Data:"
j=0
forpartinmessage.walk():
j=j+1
fileName=part.get_filename()
contentType=part.get_content_type()
mycode=part.get_content_charset();
#保存附件
iffileName:
data=part.get_payload(decode=True)
h=email.Header.Header(fileName)
dh=email.Header.decode_header(h)
fname=dh[0][0]
encodeStr=dh[0][1]
ifencodeStr!=None:
fname=fname.decode(encodeStr,mycode)
#endif
fEx=open("%s"%(fname),'wb')
fEx.write(data)
fEx.close()
elifcontentType=='text/plain':#orcontentType=='text/html':
#保存正文
data=part.get_payload(decode=True)
content=str(data);
ifmycode=='gb2312':
content=mbs_to_utf8(content)
#endif
nPos=content.find('降息')
print("nPosis%d"%(nPos))
print>>f,data
#endif
#endfor
f.close()
#endfor
pop_conn.quit()
更多关于Python相关内容可查看本站专题:《PythonSocket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。