【问题标题】:convert mailbox message to PDF: which part?将邮箱消息转换为 PDF:哪一部分?
【发布时间】:2018-04-05 21:00:31
【问题描述】:

我正在尝试编写一个脚本,该脚本将使用 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?

【问题讨论】:

  • 你试过message.get_body(preferencelist=('html','plain')):docs.python.org/3/library/…
  • 看来 get_body 不是邮箱方法。我的消息对象的类型为mailbox.mboxMessage。
  • 你为什么不做if part.get_content_type() == 'text/html':
  • 似乎有效。谢谢!

标签: python beautifulsoup


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 2012-07-02
    • 2013-07-12
    • 2018-10-09
    • 2011-07-07
    相关资源
    最近更新 更多