python - 将邮箱消息转换为 PDF : which part?

标签 python beautifulsoup

我正在尝试编写一个脚本,使用 pdfkit 将我的所有消息(邮箱 mbox 格式)导出为 PDF 文件。

似乎我邮箱中的所有邮件都是多部分的,我正在努力弄清楚哪部分是相关的部分。如果我使用下面的代码遍历所有部分,我通常会为每封电子邮件生成 3 到 5 个 PDF,其中只有一个与我使用电子邮件客户端打开电子邮件时看到的内容类似。其他部分通常是原始文本或看起来像这样的东西:x92O&S\xd2\x0c\xb4e\xee\x0fh\xc68\x1(十六进制?)。

我试图通过包含一个过滤 HTML 的测试来解决这个问题 (if bool(BeautifulSoup(html, "html.parser").find())) 但看起来确实如此不工作。

for part in message.walk():
    partcounter +=1
    try:
        html = str(part.get_payload(decode=True))
        if bool(BeautifulSoup(html, "html.parser").find()):
            print(str(messagecounter)+'-'+str(partcounter)+' - '+"payload is HTML")
            filename = 'C:/Email_forwarding/Attachments/'+str(messagecounter)+"-"+str(partcounter)+'.pdf'#this keeps the file only for the last part, which seems to be correct
            pdfkit.from_string(html,filename, configuration=config)
            print(str(messagecounter)+'-'+str(partcounter)+' - '+"created %s" %(filename))
        else:
            print(str(messagecounter)+'-'+str(partcounter)+' - '+"payload is not HTML")
    except:
        print(str(messagecounter)+'-'+str(partcounter)+' - '+"no payload or failed to convert")

如何检测多部分电子邮件的哪一部分包含实际的、可解释的 HTML?

最佳答案

您可以使用 part.get_content_type()过滤消息的不同部分:

for part in message.walk():
    if part.get_content_type() == 'text/html':
        html = str(part.get_payload(decode=True))

关于python - 将邮箱消息转换为 PDF : which part?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49671464/

相关文章:

python - 尝试索引数组时,具有多个元素的数组的真值不明确

python - 当我按 CSS 类过滤时,为什么 scrapy 和 beautifulsoup 都没有返回任何内容?

python - 我怎样才能找到图片中突出显示的元素。我用 Selenium

带有 BeautifulSoup 的 Python XMl 解析器。如何删除标签?

python - Scrapy 的代理池系统暂时停止使用慢速/超时代理

python - peewee - 为每个外键仅选择最新记录

python - Python 中的 Curl 等价物

javascript - Python - 请求/RoboBrowser - ASPX POST JavaScript

python - 仅包含 'div' s 的表的抓取

python - 如何在 Django 1.7 的表单模型中获取当前登录的用户 ID?