使用 gmail api 发送并使用 zlib 压缩时 .zip 文件被损坏

2023-12-02

我正在使用 Python 3.7 并压缩.csv使用 python 的文件zipfile and zlib.

import zipfile

filename = "report.csv"

zip_filename = f"{filename[:-4]}.zip"
with zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) as zip:
    zip.write(filename)

然后将 zip 文件附加到电子邮件中,我有一些逻辑来确定其 MIME 类型(我已检查它是否正确确定它是application/zip):

def _make_attachment_part(self, filename: str) -> MIMEBase:
    content_type, encoding = mimetypes.guess_type(filename)
    if content_type is None or encoding is not None:
        content_type = "application/octet-stream"

    main_type, sub_type = content_type.split("/", 1)
    msg = MIMEBase(main_type, sub_type)
    with open(filename, "rb") as f:
        msg.set_payload(f.read())

    base_filename = os.path.basename(filename)
    msg.add_header("Content-Disposition", "attachment", filename=base_filename)

    return msg

然后,设置主题、收件人、抄送、附件等message这是MIMEMultipart类型。然后,我用base64进行编码并发送。

raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode()

我收到了正确命名且大小符合预期的附件,但是,当我尝试使用unzip file.zip,我收到以下错误:

error [file.zip]:  missing 5 bytes in zipfile

有谁知道我做错了什么?事实上,电子邮件是从 Ubuntu 机器发送的,而我正在尝试在 MacOS 上打开收到的文件。


正如定义在rfc1341:

7BIT 编码类型要求正文已经采用七位邮件就绪表示形式。这是默认值——也就是说,如果 Content-Transfer-Encoding 标头字段不存在,则假定为“Content-Transfer-Encoding:7BIT”。

就你而言,在_make_attachment_part函数,您将有效负载设置为您的MIMEBase对象,但您没有指定内容传输编码。

我建议您将有效负载编码为 Base64。您可以按如下方式进行操作:

  1. 导入encoders module
from email import encoders
  1. 在你的里面_make_attachment_part函数,使用以下代码对您的有效负载进行编码encoders module.
def _make_attachment_part(self, filename: str) -> MIMEBase:
    content_type, encoding = mimetypes.guess_type(filename)
    if content_type is None or encoding is not None:
        content_type = "application/octet-stream"

    main_type, sub_type = content_type.split("/", 1)
    msg = MIMEBase(main_type, sub_type)
    with open(filename, "rb") as f:
        msg.set_payload(f.read())

    encoders.encode_base64(msg) # NEW

    base_filename = os.path.basename(filename)
    msg.add_header("Content-Disposition", "attachment", filename=base_filename)

    return msg
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 gmail api 发送并使用 zlib 压缩时 .zip 文件被损坏 的相关文章

随机推荐