Python实现读取邮箱中的邮件功能示例【含文本及附件】
Python  /  管理员 发布于 7年前   144
本文实例讲述了Python实现读取邮箱中的邮件功能。分享给大家供大家参考,具体如下:
#-*- encoding: utf-8 -*-import sysimport localeimport poplibfrom email import parserimport emailimport string# 确定运行环境的encoding__g_codeset = sys.getdefaultencoding()if "ascii"==__g_codeset: __g_codeset = locale.getdefaultlocale()[1]#def object2double(obj): if(obj==None or obj==""): return 0 else: return float(obj) #end if#def utf8_to_mbs(s): return s.decode("utf-8").encode(__g_codeset)#def mbs_to_utf8(s): return s.decode(__g_codeset).encode("utf-8")#host = 'pop.exmail.qq.com'username = '[email protected]'password = 'password'pop_conn = poplib.POP3_SSL(host)pop_conn.user(username)pop_conn.pass_(password)#Get messages from server:# 获得邮件messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]#print messages#print "--------------------------------------------------"# Concat message pieces:messages = ["\n".join(mssg[1]) for mssg in messages]#print messages#Parse message intom an email object:# 分析messages = [parser.Parser().parsestr(mssg) for mssg in messages]i = 0for index in range(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 for part in message.walk(): j = j + 1 fileName = part.get_filename() contentType = part.get_content_type() mycode=part.get_content_charset(); # 保存附件 if fileName: 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] if encodeStr != None: fname = fname.decode(encodeStr, mycode) #end if fEx = open("%s"%(fname), 'wb') fEx.write(data) fEx.close() elif contentType == 'text/plain':# or contentType == 'text/html': #保存正文 data = part.get_payload(decode=True) content=str(data); if mycode=='gb2312': content= mbs_to_utf8(content) #end if nPos = content.find('降息') print("nPos is %d"%(nPos)) print >> f, data #end if #end for f.close()#end forpop_conn.quit()
更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号