之前在工作中需要用到自动查收邮件和下载附件,于是用python做了一些自动化的尝试。以下代码主要实现了两个功能,一个是下载并解码邮件正文(print_info函数),另一个是下载邮件附件(get_att函数)。所有代码都已在python3.6下运行通过,不过需要修改自己邮箱的账号密码、邮箱服务器、附件保存地址。
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
import email
import poplib
#python邮件读取
def guess_charset(msg):
charset = msg.get_charset() #获取msg编码方式
if charset is None:
content_type = msg.get('Content-Type', '').lower() #获取内容类型字符串
pos = content_type.find('charset=') #内容类型中查找“charset=”字符串的位置
if pos >= 0:
charset = content_type[pos + 8:].strip() #若存在上述字符串,则返回内容类型
return charset
def decode_str(s):
value, charset = decode_header(s)[0] #Returns a list of (string, charset) pairs
if charset: