gpt4 book ai didi

python - 将电子邮件附件保存到 python 2.7 中的文件

转载 作者:行者123 更新时间:2023-11-28 21:55:12 25 4
gpt4 key购买 nike

你好,我有一个类似的问题:

Getting mail attachment to python file object

我想将电子邮件中的所有文件附件保存到我硬盘上的文件中。但如果我是正确的,并非多部分电子邮件的所有部分都是“真实”文件(例如,电子邮件 html 部分中的一些图像)。我想 100% 确定我保存的文件是附件。

现在我有这个:

mail = "";
for line in sys.stdin:
mail += line;

msg = email.message_from_string(mail);

for part in msg.walk():
check if is file and save

最佳答案

基于 http://www.ianlewis.org/en/parsing-email-attachments-python

我设法创建了这段代码:

import sys;
import email

class Attachement(object):
def __init__(self):
self.data = None;
self.content_type = None;
self.size = None;
self.name = None;



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"):

attachment = Attachement();
attachment.data = message_part.get_payload(decode=True);
attachment.content_type = message_part.get_content_type();
attachment.size = len(attachment.data);
attachment.name = message_part.get_filename();

return attachment;

return None;


if __name__=='__main__':

mail = "";
for line in sys.stdin:
mail += line;


msg = email.message_from_string(mail);

attachements = list();

if(msg.is_multipart()):
for part in msg.walk():
attachement = parse_attachment(part);
if(attachement):
attachements.append(attachement);




for att in attachements:
# write file in binary mode
file = open(att.name, 'wb');
file.write(att.data);
file.close();



print 'OK';

关于python - 将电子邮件附件保存到 python 2.7 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23080859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com