将文件作为附件发送 Django

Sending files as an attachment Django

我创建了一个 XLS 文件并想将其作为电子邮件附件发送。以下代码运行良好,我收到一封包含 XLS 文件的电子邮件(状态代码为 200 OK)。

# This is working code
import xlwt
import StringIO
import zipfile

from django.core.mail import EmailMessage


work_book = xlwt.Workbook()

# Here some boring stuff with excel
...

report_name = "do_something_%(username)s_%(current_date)s.xls"

f = StringIO.StringIO()
work_book.save(f)

message = EmailMessage(
    subject=u"Sample Title",
    body=u"Sample body",
    to=["test@company.com"])

message.attach(report_name, f.getvalue())
message.send()

但是如果我尝试发送压缩的 XLS 文件(使用 zipfile),我没有收到任何东西(但是状态代码是“200 OK”)。 我用以下代码替换了最后两行代码:


report_name_zip = 'do_something_%(username)s_%(current_date)s.zip'

with zipfile.ZipFile(f, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
    zf.writestr(zinfo_or_arcname=report_name, bytes=f.getvalue())

message.attach(report_name_zip, f.getvalue())
message.send()

您对 stringIO 进行读写操作。您应该使用两个单独的 StringIOs:

report_name_zip = 'do_something_%(username)s_%(current_date)s.zip'

report_name = "do_something_%(username)s_%(current_date)s.xls"

<b>f1</b> = StringIO.StringIO()
work_book.save(<b>f1</b>)

<b>f2</b> = StringIO.StringIO()
with zipfile.ZipFile(<b>f2</b>, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
    zf.writestr(zinfo_or_arcname=report_name, data=<b>f1</b>.getvalue())

message.attach(report_name_zip, <b>f2</b>.getvalue())
message.send()