首页 > 解决方案 > 直接在内存上压缩读取的文件数据(用于电子邮件)

问题描述

我编写了一个代码来通过 Python 上的 SMTP 发送电子邮件。在代码的某些部分,我将一些文件附加到电子邮件正文中,有时这个附件大于 25MB(或接近),我想压缩它。

由于服务限制,我不会在文件夹上创建 zip/gz/tar/...,而只是压缩已经读取的内容data以获得compressed_data看起来与压缩读取文件相同的字节流。可能吗?

def add_attachment(file_path: str,id_value: Optional[str] = None, compress_file: Optional[bool] = False):
    '''Add an attachment or image to be used into the message.

    Parameters:
        File path
        Image id for the HTML use case.
        Compress the file.
    '''
    filename = os.path.split(file_path)[1]
    # Guess the content type based on the file's extension.
    ctype, encoding = mimetypes.guess_type(file_path)
    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    with open(file_path, 'rb') as fp:
        file_size = os.fstat(fp.fileno()).st_size
        if file_size >= EMAIL_MAX_ATTACH_SIZE:
            compress_file = True  # Force compression.
        file_data = fp.read()
        # Compress the file before send (it is asked to or the uncompressed file size surpasses the e-mail attachment limit).
        if compress_file:
            pass #TODO
        # Get the file type.
        if maintype == 'application':
            mime_file = MIMEApplication(file_data, subtype, name=filename)
        elif maintype == 'image':
            mime_file = MIMEImage(file_data, subtype,name=filename)
        else:
            return
        # Add the ID to the attachment content.
        if id_value:
            mime_file.add_header('Content-ID', id_value)
        else:
            mime_file.add_header('Content-ID', '<' + os.path.splitext(filename)[0] + '>')
        # Add the attachment to the e-mail
        msg_root.attach(mime_file)

标签: pythonsmtpcompression

解决方案


推荐阅读