#!/usr/bin/env python
#coding=utf-8
import poplib
import StringIO
import string
import rfc822
import email
host='pop3.163.com'
username='xxx000
password='xxxooo'
#发送主机名
p = poplib.POP3(host)
#打开调试模式
#p.set_debuglevel(1)
#发送用户名
p.user(username)
#发送密码
p.pass_(password)
#获取消息数量跟消息的总大小
status = p.stat()
print "Mailbox has %d messages for a total of %d bytes" %(status[0], status[1])
#服务器的返回信息,邮件顺序列表,信息的大小
msg = p.list()
#显示每封邮件的大小
for item in msg[1]:
#把字符串转化为列表
number, octets = item.split(' ')
print "Message %s: %s bytes" %(number, octets)
#邮件下载
mesgg = p.retr(number)
text = string.join(mesgg[1],"\n")
#s = StringIO.StringIO()
#s.write(text)
#s.seek(0)
#pr = s.read()
#print pr
#将邮件送如缓冲区
s = StringIO.StringIO(text)
#将文件指针移动到字符开始处
#s.seek(0)
#用rfc822处理邮件头部
#message = rfc822.Message(s)
#print "Subject: ", message.get('subject')
#print "From: ", message.getaddr('from')
#print "To: ", message.getaddrlist('to')
#print "DATA: ", message.getdate('date')
#print
s.seek(0)
#用email模块处理邮件头部,这个模块更好
message = email.message_from_file(s)
#邮件主题
su = email.Header.decode_header(message['subject'])
#发件人
fr = email.Header.decode_header(message['from'])
#收件人
to = email.Header.decode_header(message['to'])
#邮件接收时间
da = email.Header.decode_header(message['date'])
print "Subject: ", su[0][0]
print "From: ", fr[0][0]
print "To: ", to[0][0]
print "DATA: ", da[0][0]
print
p.quit()
运行结果: