Skip to main content
 首页 » 编程设计

python之如何使用 email.Parser 从文件中提取电子邮件正文

2024年08月25日33tuyile006

我正在尝试使用 python 和 email.Parser 从文件中解析电子邮件。我使用以下命令

headers = Parser().parse(open(filename, 'r')) 

解析文件。但是当我尝试获取 body 时,我使用例如

print(headers.get_payload()[0]) 

我得到类似的东西

From nobody Mon Oct 12 16:32:25 2015 
Content-Type: text/plain; charset=UTF-8 
Content-Transfer-Encoding: quoted-printable 
 
Hi Alex, 
.... 

有什么方法可以去掉前三/四行吗?以及如何解码“fr=C3=BCer”之类的内容?

请您参考如下方法:

要到达消息正文,您必须 walk() 它的不同部分,即:

a = email.message_from_file(open(filename, 'r')) #shorthand for Parser().parse 
body = '' 
 
if a.is_multipart(): 
   for part in b.walk(): 
       ctype = part.get_content_type() 
       cdispo = str(part.get('Content-Disposition')) 
 
       # skip any text/plain (txt) attachments 
       if ctype == 'text/plain' and 'attachment' not in cdispo: 
           body = part.get_payload(decode=True)  # decode 
           break 
# not multipart - i.e. plain text, no attachments 
else: 
    body = b.get_payload(decode=True) 

get_payload() 中的 decode=True 进行 base64/etc 解码,即 'fr=C3=BCer' 字符串