Home > front end >  Add Encoded Zip File to MIMEtype using python
Add Encoded Zip File to MIMEtype using python

Time:04-18

I'm Trying to Encode the zip file as byte data and I try to append Byte data to Mimefile using python with these function


# encoder.py

from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def convert_mimetype(xml_string, zipfile):
    """
    mime-type converter
    """

    # messages construct
    messages = MIMEMultipart(
        "related",
        boundary="MIMEBoundary",
    )
    messages.add_header(
        "Content-Description",
        "This Transmission File is created with Pegasus Test Suite",
    )
    messages.add_header("X-eFileRoutingCode", "MEF")

    xml_str = xml_string.decode("UTF-8")
    messages.attach(
        MIMEText(
            xml_str,
            "xml",
        )
    )

    files_path = f"{ROOT_PATH}/attachments/zipfile/{zipfile}"

    attachment = open(files_path, "rb").read()

    # part construct
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment)
    part.add_header("Content-Transfer-Encoding", "Binary")
    part.add_header("Content-Location", "SubmissionZip")

    messages.attach(part)

    print(f"Type of MimeData: {type(messages)}")

    # generate report
    report_filename = zipfile.replace('.zip', '')
    with open(f"{ROOT_PATH}/reports/{report_filename}.trn.txt", "wb") as mimefiles:
        mimefiles.write(bytes(messages))

    print(f"Mime Report Generated on {ROOT_PATH}/reports/{report_filename}.trn.txt")
    return str(messages)

the result file is

Content-Type: multipart/related; boundary="MIMEBoundary"
MIME-Version: 1.0
Content-Description: This Transmission File is created with Pegasus Test Suite
X-eFileRoutingCode: MEF

--MIMEBoundary
Content-Type: text/xml; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

<?xml version='1.0' encoding='UTF-8'?>
<SOAP:Envelope xmlns="http://www.irs.gov/efile" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" xmlns:efile="http://www.irs.gov/efile" xsi:schemaLocation="http://schemas.xmlsoap.org/soap/envelope/ ../message/SOAP.xsd http://www.irs.gov/efile ../message/efileMessage.xsd"><SOAP:Header><IFATransmissionHeader><MessageId>012342018ABCDEFGHIJK</MessageId><TransmissionTs>2018-07-01T09:51:56-05:00</TransmissionTs><TransmitterDetail><ETIN>XXXXX</ETIN></TransmitterDetail></IFATransmissionHeader></SOAP:Header><SOAP:Body><TransmissionManifest><SubmissionDataList><Cnt>1</Cnt><SubmissionData><SubmissionId>0123452018OPQRSTUVWX</SubmissionId><ElectronicPostmarkTs>2018-07-01T09:51:56-05:00</ElectronicPostmarkTs></SubmissionData></SubmissionDataList></TransmissionManifest></SOAP:Body></SOAP:Envelope>
--MIMEBoundary
Content-Type: application/octet-stream
MIME-Version: 1.0
Content-Transfer-Encoding: Binary
Content-Location: SubmissionZip

Encoded zip

encoded zip file

the zip file is corrupt if I decode using ripmime and another application the .zip file is still corrupt, I've to try to create an object using byte of zip file using

def decode_process(zip_path, decoded_filename):
    try:
        os.mkdir(f"{ROOT_PATH}/temp")
    except FileExistsError:
        pass

    try:
        os.mkdir(f"{ROOT_PATH}/temp/encoder")
    except FileExistsError:
        pass
    
    with open(zip_path, "rb") as zip_data:
        # read encoding
        byte_data = zip_data.read()


        with open(f"{ROOT_PATH}/reports/zipfile_report/{decoded_filename}", 'wb') as archiver:
            archiver.write(byte_data)
        print("achiver writted")

        print('Creating binary file')
        filename = decoded_filename.replace('.zip', '')
        with open(f'{ROOT_PATH}/temp/encoder/{filename}.txt', 'wb') as binary_obj:
            binary_obj.write(byte_data)
        
        print(f"{filename}.text Binary file Created on temp/encoder/ dir")

and I'm trying to create a zip file from the object file I just created using the function

def convert_zip_from_obj_file(filename):
    with open(f'{ROOT_PATH}/temp/encoder/{filename}', 'rb') as bytefile:
        bin_data = bytefile.read()


        # write zip file
        with open(f'{ROOT_PATH}/reports/zipfile_report/{filename}.zip'.replace('.txt', '_report'), 'wb') as archiver:
            archiver.write(bin_data)
        print(f'Archive generated from {filename} file on {ROOT_PATH}/reports/zipfile_report/ directory')

and the zip file is successfully created without a corrupt zip file but if I append to Mime and I decode I got the corrupt zip file

what encoding should I use so that the file doesn't get corrupted when added to the mime type, how do I encode and decode it? if I using python

CodePudding user response:

try to add content, not as payload but as an attachment on mime using MIMEApplications Classes

xml_str = xml_string.decode("UTF-8")
messages.attach(
        MIMEText(
        xml_str,
        "XML",
    )
)

# message
messages.attach(MIMEApplication(data, "octet-stream"))
messages.add_header("Content-Transfer-Encoding", "Binary")
messages.add_header("Content-Location", f"{foldername}")

and try to encode as Base64 or return as string

with open(f"{ROOT_PATH}/reports/{foldername}.trn.txt", "w") as mimefiles:
            mimefiles.write(messages.as_string())
  • Related