Logman
Logman

Reputation: 4189

Save email attachment to file in python 2.7

Hi I have a similar question to this:

Getting mail attachment to python file object

I want to save all files attachments to files on my hard drive from email. But if I am correct not all parts of multipart email are "real" files (for ex. some images in html part of email). I want to be 100% sure that files I save are attachments.

for now I have this:

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

Upvotes: 2

Views: 7153

Answers (1)

Logman
Logman

Reputation: 4189

Base on http://www.ianlewis.org/en/parsing-email-attachments-python

I manage to create this code:

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

Upvotes: 5

Related Questions