python - 在内存中创建一个 ZipFile 并将其附加到电子邮件中

标签 python python-2.7 email-attachments in-memory python-zipfile

我正在尝试修改现有的 python 脚本,以将内存中的 CSV 转换为(也在内存中)zip 存档,并将其作为电子邮件的附件发送。我已成功附加内存中的 CSV 文件(通过 MIMEText 对象),但由于需要设置文件字节的有效负载,因此在处理 ZIP 文件(通过 MIMEBase 对象)时遇到问题。

这是我到目前为止的代码:

csv_buffer = cStringIO.StringIO()
buffer = cStringIO.StringIO()

zf = zipfile.ZipFile(buffer,
               mode='w',
               compression=zipfile.ZIP_DEFLATED,
               )

zf.writestr(csvfile + ".csv", csv_buffer.getvalue())


csv_file = MIMEBase('application', 'zip')
csv_file.set_payload(zf.read())
encoders.encode_base64(csv_file)
csv_file.add_header('Content-Disposition', 'attachment',
         filename=csvfile + ".zip")

msg.attach(csv_file)

从此This user's most upvoted answer我可以通过对 zip 文件执行正常的 open() 操作来修复我收到的 read() 需要至少 2 个参数 错误,但由于该文件是缓冲的无法正常工作的流。

我不确定如何将 zipfile 对象加载到 set_payload 中,但我认为这也应该有效。

最佳答案

read方法ZipFile对象旨在读取 zip 文件中指定文件的内容。

您应该使用 buffer 的内容相反,在使用 writestr 写入缓冲区之后ZipFile的方法实例:

csv_file.set_payload(buffer.getvalue())

关于python - 在内存中创建一个 ZipFile 并将其附加到电子邮件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61087476/

相关文章:

python - 如何排除一最小和一最大数字?

python - 如何在 Keras 中计算精度和召回率

python - 计算总和的结果连续多少次为正(或负)

Python plotly : use buttons to update sets of subplots & arbitrarily assign traces

python - long 的结构长度取决于字节顺序?

excel - 附加某些文件

python - 在 python 中获取列表和 JSON 输出之间的差异

python - re.Pattern.findall 工作错误

c# - 带有长非 ASCII 名称的电子邮件附件

python-3.x - 电子邮件未发送excel附件