来自邮箱messag的电子邮件的非递归遍历

2024-04-23 17:44:37 发布

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

我正尝试在python3.7中处理电子邮件,并努力解决一些看起来像是兼容性问题的问题。文档提到email.message.Message有一个iter_parts方法,该方法允许我对消息部分进行非递归遍历。你知道吗

这在从mailbox消息返回的消息上不存在,我花了一段时间才让它正常工作。例如,我可以生成一个伪消息:

from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'msg 1'
msg.add_alternative("Plain text body", subtype='plain')
msg.add_alternative("<html><body><p>HTML body</p></body></html>", subtype='html')
msg.add_attachment(b"Nothing to see here!", maintype='data', subtype='raw')

然后把零件倒出来:

def iter_parts(msg):
  ret = msg.get_content_type()
  if msg.is_multipart():
    parts = ', '.join(iter_parts(m) for m in msg.iter_parts())
    ret = f'{ret} [{parts}]'
  return ret

iter_parts(msg)

这给了我:multipart/mixed [multipart/alternative [text/plain, text/plain], data/raw]

但是如果我把它保存到一个mbox文件并重新加载它:

import mailbox
mbox = mailbox.mbox('/tmp/test.eml')
mbox.add(msg)
iter_parts(mbox[0])

它告诉我AttributeError: 'mboxMessage' object has no attribute 'iter_parts'

起初我认为它可能与https://stackoverflow.com/a/45804980/1358308有关,但在python3.7中设置factory=None似乎没有什么作用。你知道吗

我张贴我的解决方案,但想知道是否有更好的选择!你知道吗


Tags: textadd消息htmlbodymsgpartsmultipart
1条回答
网友
1楼 · 发布于 2024-04-23 17:44:37

在对源代码进行了大量的挖掘和阅读之后,我发现我可以:

from email import policy
from email.parser import BytesParser

mbox = mailbox.mbox('/tmp/test.eml', factory=BytesParser(policy=policy.default).parse)

然后我用iter_parts方法得到对象。你知道吗

相关问题 更多 >