我需要从电子邮件中提取一个msg类型的附件,并将msg附件保存到python中的某个位置
我编写的脚本适用于除outlook项以外的几乎所有类型的文件
def parse_attachment(message_part):
content_disposition = message_part.get("Content-Disposition", None)
if content_disposition:
dispositions = content_disposition.strip().split(";")
if bool(content_disposition and (dispositions[0].lower() == "attachment" or dispositions[0].lower() == "inline")):
file_data = message_part.get_payload(decode=True)
debug(message_part)
attachment = {}
attachment['data'] = file_data
attachment['content_type'] = message_part.get_content_type()
attachment['size'] = len(file_data)
for param in dispositions[1:]:
name,value = param.split("=")
name = name.lower().strip()
value = value.strip().strip("\"")
if name == "filename":
attachment['name'] = value
elif name == "creation-date":
attachment['creation-date'] = value
elif name == "modification-date":
attachment['modification-date'] = value
elif name == "size":
attachment['size'] = value
return attachment
return None
我们必须单独处理电子邮件附件。但是,如果我们使用
walk()
,这是一个通用的生成器,可以用来迭代消息对象树的所有部分和子部分,按照深度优先遍历顺序,我们也会解析附件电子邮件因此,我们必须使用
get_payload()
来获取电子邮件的每一部分。下面是我们如何解析电子邮件附件-相关问题 更多 >
编程相关推荐