一些背景信息...
不久前,我编写了一个处理电子邮件的Python程序,其中一个经常遇到的问题是要知道电子邮件是否为“多部分”的。
经过一番调查,我知道这与电子邮件中包含HTML或附件等有关...但我并没有真正理解它。
我的使用仅限于2个实例:
1. 当我需要保存原始电子邮件中的附件时
我在互联网上找到了这个代码(可能在这里 - 对不起,我无法再找到他了,未能给出作者的名字 :/),并将其粘贴到我的代码中。
def downloadAttachments(emailMsg, pathToSaveFile):
"""
Save Attachments to pathToSaveFile (Example: pathToSaveFile = "C:\\Program Files\\")
"""
att_path_list = []
for part in emailMsg.walk():
# multipart are just containers, so we skip them
if part.get_content_maintype() == 'multipart':
continue
# is this part an attachment ?
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
att_path = os.path.join(pathToSaveFile, filename)
#Check if its already there
if not os.path.isfile(att_path) :
# finally write the stuff
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
att_path_list.append(att_path)
return att_path_list
2. 当我需要从原始电子邮件中获取文本时
也曾经从互联网上复制黏贴过来,但并不真正了解其工作原理。
def get_text(emailMsg):
"""
Output: body of the email (text content)
"""
if emailMsg.is_multipart():
return get_text(emailMsg.get_payload(0))
else:
return emailMsg.get_payload(None, True)
我所了解的是...
如果电子邮件消息是多部分的,那么这些部分可以被遍历。
我的问题是
究竟是什么构成了这些部分?如何知道哪个是html?或者哪个是附件?或者只是正文?
part.get('Content-Disposition')
为None
,那么这是不正确的。这只是告诉你这个部分没有显式的处理方式;因此你必须推断出一个隐含的处理方式,这取决于该部分的类型。text/*
通常是隐含内联的,而大多数其他类型则是隐含附件的。 - tripleeeget_text()
同样很简单。如果您想决定要显示的“消息”,则应避免明确标记为Content-Disposition: attachment
或嵌入在例如退回消息中的部分。如果存在multipart/alternative
(实际上可能同样标记为multipart/mixed
或multipart/related
),则可能会有多个消息正文的呈现方式,您可以选择适合您用例的那一个。 - tripleee