def parse_attachment(message_part): """Function to parse attachment from MIME message part. Args: message_part (obj): part in the MIME message object tree. Returns: obj of either StringIO (for strings) else BytesIO. If no attachments were present, 'None' is returned. """ content_disposition = message_part.get("Content-Disposition", None) content_id = message_part.get("Content-ID", None) if content_disposition: dispositions = content_disposition.strip().split(";") if (content_disposition and (dispositions[0].lower() == "attachment" or dispositions[0].lower() == "inline")): file_data = message_part.get_payload(decode=True) if isinstance(file_data, str): attachment = StringIO(file_data) else: attachment = BytesIO(file_data) attachment.content_type = message_part.get_content_type() attachment.size = len(file_data) attachment.name = None attachment.create_date = None attachment.mod_date = None attachment.read_date = None attachment.disposition = dispositions[0] attachment.id = content_id for param in dispositions[1:]: name, value = param.strip().split("=") name = name.lower() value = value.replace('"', "") value = value.replace("'", "") if name == "filename": attachment.name = value elif name == "create-date": attachment.create_date = value # TODO: datetime elif name == "modification-date": attachment.mod_date = value # TODO: datetime elif name == "read-date": attachment.read_date = value # TODO: datetime return attachment return None
def parse_attachment(message_part): content_disposition = message_part.get("Content-Disposition", None) content_id = message_part.get("Content-ID", None) if content_disposition: dispositions = content_disposition.strip().split(";") if (content_disposition and (dispositions[0].lower() == "attachment" or dispositions[0].lower() == "inline")): file_data = message_part.get_payload(decode=True) if isinstance(file_data, str): attachment = StringIO(file_data) else: attachment = BytesIO(file_data) attachment.content_type = message_part.get_content_type() attachment.size = len(file_data) attachment.name = None attachment.create_date = None attachment.mod_date = None attachment.read_date = None attachment.disposition = dispositions[0] attachment.id = content_id for param in dispositions[1:]: name, value = param.strip().split("=") name = name.lower() value = value.replace('"', "") value = value.replace("'", "") if name == "filename": attachment.name = value elif name == "create-date": attachment.create_date = value #TODO: datetime elif name == "modification-date": attachment.mod_date = value #TODO: datetime elif name == "read-date": attachment.read_date = value #TODO: datetime return attachment return None