【发布时间】: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