python - 直接在内存上压缩读取的文件数据(用于电子邮件)
问题描述
我编写了一个代码来通过 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)
解决方案
推荐阅读
- reactjs - 在条件 HTML 链接上反应意外的令牌
- compilation - “内存中二进制内存映像”是什么意思?
- windows - 无法从 echo $PATH 中删除路径
- c++ - 为什么在 Main 中正常运行的代码在函数内部运行不正确?(C++)
- c++ - C++ 中的适配器模式返回分段错误
- mongodb - WSo2 tls 连接到 mongodb 数据服务
- java - slf4j 找不到 log4j2 jar
- vue.js - 如何在vue组件的样式标签中添加if
- discord.js - 我正在尝试发出命令来显示不和谐机器人在多少台服务器上,但得到错误“消息未定义”
- apache-kafka - Kafka Manager - 需要跟踪使用它的用户以确保安全