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

时间:2014-04-15 10:18:23

标签: python email python-2.7

您好我有类似的问题:

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

1 个答案:

答案 0 :(得分:3)

基于 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';