Skip to content Skip to sidebar Skip to footer

.zip File Gets Corrupted When Sent With Gmail Api And Compressed With Zlib

I am using Python 3.7 and compressing a .csv file using python's zipfile and zlib. import zipfile filename = 'report.csv' zip_filename = f'{filename[:-4]}.zip' with zipfile.ZipF

Solution 1:

As defined in the rfc1341:

An encoding type of 7BIT requires that the body is already in a seven-bit mail- ready representation. This is the default value -- that is, "Content-Transfer-Encoding: 7BIT" is assumed if the Content-Transfer-Encoding header field is not present.

In your case, in the _make_attachment_part function, you are setting the payload to your MIMEBase object, but you are not specifying the Content-Transfer-Encoding.

I suggest that you encode your payload as Base64. You can do it as follows:

  1. Import the encoders module
from email import encoders
  1. Inside your _make_attachment_part function, encode your payload using the 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

Post a Comment for ".zip File Gets Corrupted When Sent With Gmail Api And Compressed With Zlib"