Logman Logman - 1 year ago 259
Python Question

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

Answer Source

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();

        for part in msg.walk():
            attachement = parse_attachment(part);

    for att in attachements:
        file = open(att.name, 'w');

    print 'OK';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download