【问题标题】:Why doesn't python's email parser find all parts of this multipart MIME email?为什么 python 的电子邮件解析器找不到这封多部分 MIME 电子邮件的所有部分?
【发布时间】:2016-06-04 16:30:37
【问题描述】:

我正在尝试使用 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)

输出(请注意,printing 部分中没有最后的“应用程序/pdf”部分):

multipart/alternative
text/plain
text/html
False

消息本身,剪掉以显示重要部分:

--_=_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_=_-- 包裹的第一个“部分”中。我认为这是相关的,但谷歌和 SO 搜索失败,所以我在这里。

【问题讨论】:

    标签: python email parsing mime multipart


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-10-05
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 2014-11-08
      • 2014-06-21
      • 2020-06-30
      相关资源
      最近更新 更多