POP(Post Office Post),邮局协议,采用C/S工作模式,读取电子邮件的过程是先利用DNS协议解析POP服务器的IP地址,并连接服务器,使用USER命令将密码传入POP服务器,使用PASS命令将密码传入POP服务器,这个过程完成后,就完成了POP服务器认证,接下来可以对邮箱内的邮件做进一步的操作,python中的poplib库提供了许多方法,如stat,list等,这些方法可以查看邮箱内的邮件数量,大小,下载其中的邮件等。
用python连接和认证一个远程服务器并读取邮件,需要先建立一个POP3对象,传入服务器的主机名和端口号,使用user()和pass_()方法来发送用户名和密码,使用stat()方法获取邮件列表,使用list()方法显示邮件的信息。
下面是程序:
#!/usr/bin/env python import sys,poplib,getpass,email (host,user,file)=sys.argv[1:] passwd =getpass.getpass() p=poplib.POP3(host) fd=open(file,"at") try: p.user(user) p.pass_(passwd) except poplib.error_proto,e: print "failed to login in" sys.exit(-1) mail=p.stat() print “There’re %d messages and the total size if %d bytes” %(mail[0],mail[1]) for item in p.list()[1]: number,bytes=item.split(‘ ‘) lines=p.retr(number)[1] msg=email.message_from_string("\n".join(lines)) fd.write(msg.as_string(unixfrom=1)) fd.write(‘\n‘) p.quit() fd.close()ubuntu环境运行上面的程序,会在当前目录生成一个文件,用cat命令就可以查看邮件内容了。
原文:http://blog.csdn.net/u011608357/article/details/19760259