为什么python的电子邮件解析器没有找到这个多部分MIME电子邮件的所有部分?

2024-04-25 23:35:33 发布

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

我试图使用Python的email module处理一个简单的多部分MIME电子邮件。但是,由于某些原因我不明白,我无法浏览电子邮件的所有部分-由于某些原因,应用程序/pdf被排除在外。在

失败操作示例:

import email    

msgstring = '''See bottom of post'''

msg = email.message_from_string(msgstring)

has_pdf_attached = False

for part in msg.walk():
    print (part.get_content_type())
    if part.get_content_type() == 'application/pdf':
        payload = part.get_payload(decode=True)
        if '%PDF-' in payload:
            has_pdf_attached = True

print(has_pdf_attached)

输出(请注意,最后的“application/pdf”部分不在部件的print中):

^{pr2}$

信息本身,被剪断以显示重要信息:

--_=_swift_v4_145618772756cba94f8fcc2_=_
Content-type: multipart/alternative; boundary="----------=_1456187728-18401-69"

This is a multi-part message in MIME format...

------------=_1456187728-18401-69
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

A bunch of content here
foobar
barfoo
etc

------------=_1456187728-18401-69
Content-Type: text/html; charset="utf-8"
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

<html><body>
    <p>HTML version of content</p>
</body></html>

------------=_1456187728-18401-69--

--_=_swift_v4_145618772756cba94f8fcc2_=_
Content-Type: application/pdf; name test.pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename test.pdf

A_Big_Long_Base64_Enconded_PDF_File_foofoofoofoofoofoofoofoo
JVBER0OUMyNzc0ODFDODAwMTI+IF0KL0RvY0NoZWNrFADSFsfsaFdsafsdaf
dHhyZWYKMzE4MjkKJSVFT0YKFDSFDSFdsfdsfdsfdsfdsfdsfdsfdsfdsfds

--_=_swift_v4_145618772756cba94f8fcc2_=_--

我做错什么了?我注意到“检测到的”部分都在第一个“部分”中,由神秘的对我来说--_=_swift_v4_145618772756cba94f8fcc2_=_--包装。我想这是相关的,但谷歌和搜索失败了,所以我在这里。在


Tags: ofingetpdfapplicationemailtypecontent
1条回答
网友
1楼 · 发布于 2024-04-25 23:35:33

在标准的堆栈溢出体验中,我所要做的就是公开提出问题,然后简单的答案就会在我眼前显现出来。在

我的msgstring没有包含完整的原始电子邮件-我使用的IMAP库配置错误,正在删除邮件的主标题。 _=_swift_v4_145618772756cba94f8fcc2_=_确实是一个边界-整个多部分消息的主要边界。在

当我以msgstring形式输入实际的完整消息时,它就像一个符咒。在

把这个愚蠢的问题归结为不太了解MIME格式。在

相关问题 更多 >