Web Services 使用python将编码的Zip文件添加到MIME类型

ws51t4hk  于 2022-11-15  发布在  Python
关注(0)|答案(1)|浏览(167)

我正在尝试将zip文件编码为字节数据,并尝试使用Python将字节数据附加到Mimefile中

# 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)

结果文件是

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

如果我使用ripmime和另一个应用程序解码的zip文件仍然损坏.zip文件,我必须尝试使用zip文件的字节创建一个对象

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")

我尝试使用函数从刚创建的对象文件创建一个zip文件

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

和zip文件成功创建没有损坏的zip文件,但如果我附加到Mime和我解码,我得到了损坏的zip文件
我应该使用什么编码,使文件不被损坏时,添加到mime类型,我如何编码和解码它?如果我使用python

lmvvr0a8

lmvvr0a81#

尝试使用MIMEApplications类在mime上添加内容,而不是作为有效负载,而是作为附件

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}")

并尝试编码为Base64或返回为字符串

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

相关问题