使用emaildata 0.3.4使用Python 3.6读取.eml文件

2024-05-23 18:42:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python3.6.1,我想读入电子邮件文件(.eml)进行处理。我正在使用emaildata 0.3.4包,但是每当我尝试像在文档中那样导入文本类时,就会出现模块错误:

import email
from email.text import Text
>>> ModuleNotFoundError: No module named 'cStringIO'

当我试图使用this update更正时,我得到了与mimetools相关的下一个错误

>>> ModuleNotFoundError: No module named 'mimetools'

是否可以将emaildata 0.3.4与python 3.6一起用于解析.eml文件?或者还有其他包可以用来解析.eml文件吗?谢谢


Tags: 模块文件no文档文本import电子邮件email
1条回答
网友
1楼 · 发布于 2024-05-23 18:42:31

使用电子邮件包,我们可以读取.eml文件。然后,使用BytesParser库解析文件。最后,使用plain首选项(对于纯文本)和get_body()方法以及get_content()方法来获取电子邮件的原始文本。

import email
from email import policy
from email.parser import BytesParser
import glob
file_list = glob.glob('*.eml') # returns list of files
with open(file_list[2], 'rb') as fp:  # select a specific email file from the list
    msg = BytesParser(policy=policy.default).parse(fp)
text = msg.get_body(preferencelist=('plain')).get_content()
print(text)  # print the email content
>>> "Hi,
>>> This is an email
>>> Regards,
>>> Mister. E"

当然,这是一个简单的例子-没有提到HTML或附件。但问题问什么,我想做什么,基本上都能做到。

下面是您如何遍历多个电子邮件并将每个电子邮件保存为纯文本文件的方法:

file_list = glob.glob('*.eml') # returns list of files
for file in file_list:
    with open(file, 'rb') as fp:
        msg = BytesParser(policy=policy.default).parse(fp)
        fnm = os.path.splitext(file)[0] + '.txt'
        txt = msg.get_body(preferencelist=('plain')).get_content()
        with open(fnm, 'w') as f:
            print('Filename:', txt, file = f) 

相关问题 更多 >