使用Python添加编码的ZIP文件到MimeType

发布于 2025-01-21 08:26:36 字数 4825 浏览 1 评论 0原文

我正在尝试将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

“编码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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼性发作 2025-01-28 08:26:36

尝试使用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())

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())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文