Python: 如何在注意图结构的同时遍历MIME消息树?

Python: How to iterate over MIME message tree while taking notice of the graph structure?

我想知道如何在 Python 中获取 MIME 消息图结构(例如,作为邻接矩阵)。

根据官方 Python3 文档,有一种 email.walk() 方法可以遍历所有消息部分:

for part in email.walk():
   print(part.get_content_type())

但是输出不显示消息的层次结构。例如,以下输出:

multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
text/plain

可以表示这两种树结构中的任意一种:

multipart/report
    text/plain
    message/rfc822
        text/plain
        text/plain
    message/rfc822
        text/plain

multipart/report
    text/plain
    message/rfc822
        text/plain
        text/plain
        message/rfc822
            text/plain

python 中是否有任何方法可以帮助确定 MIME 消息的确切层次(图形)结构?

假设您已将电子邮件读入变量 email

然后如果你这样做 print(email.get_content_type()) 它应该显示类似 multipart/report 的东西(以你提供的例子为例)。

那你可以试试

if email.is_multipart():
    for subpart in email.get_payload():
        print(email.get_content_type())

然后这将打印

text/plain
message/rfc822

如果您将您提供的第二个树结构视为示例。

您可以对电子邮件的任何部分执行上述操作;如果它是多部分的,那么它基本上会将其分解成它的组件。

您可以使用它来创建一个递归函数,该函数可能会在打印部分的内容类型之前打印一个制表符,具体取决于嵌套的深度。

自从我上次使用电子邮件以来已经有一段时间了,但这应该可以解决问题。