网上Python发送邮件的程序很多,但是很少有读取邮件的程序。一个朋友遇到了问题,咨询我如何读取message的信息。我就把我最终的代码分享给大家。希望对大家能有帮助。但是由于很少使用简书,不会像大拿那样很漂亮地显示代码,可能格式会有点问题。若遇到问题的朋友,可以留言,我会把源文件发给你。
import imaplib
import email
import base64
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
def decode_str(s):
value, charset = decode_header(s)[0]
if charset:
value = value.decode(charset)
return value
def guess_charset(msg):
charset = msg.get_charset()
if charset is None:
content_type = msg.get('Content-Type', '').lower()
pos = content_type.find('charset=')
if pos >= 0:
charset = content_type[pos+8:].strip()
return charset
def print_info(msg, indent=0):
if indent == 0:
for header in ['From', 'To', 'Subject', 'Date']:
value = msg.get(header, '')
if value:
if header=='Subject':
value = decode_str(value)
elif header == 'Date':
value = value
else:
hdr, addr = parseaddr(value)
name = decode_str(hdr)
value = u'%s <%s>' % (name, addr)
print('%s%s: %s' % (' ' * indent, header, value))
if (msg.is_multipart()):
parts = msg.get_payload()
for n, part in enumerate(parts):
print('%spart %s' % (' ' * indent, n))
print('%s--------------------' % (' ' * indent))
print_info(part, indent + 1)
else:
content_type = msg.get_content_type()
if content_type=='text/plain' or content_type=='text/html':
content = msg.get_payload(decode=True)
charset = guess_charset(msg)
if charset:
content = content.decode(charset)
print('%sText: %s' % (' ' * indent, content + '...'))
else:
print('%sAttachment: %s' % (' ' * indent, content_type))
if __name__=='__main__':
conn=imaplib.IMAP4_SSL('imap.qq.com','993')conn.login('帐号','密码')
print('已登录')
result, message =conn.select()
type, data = conn.search(None, 'ALL')
newlist=data[0].split()
for i in range(0, len(newlist)): #测试发现只读取最新的204封邮件。
type, data = conn.fetch(newlist[i], '(RFC822)') #选择邮件
msg = email.message_from_string(data[0][1].decode('utf-8'))
print_info(msg)