I have created an XLS file and want to send it as an attachment to an email. The following code is working fine and I receive an email with the XLS file (status code is 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()
But if I try to send compressed XLS file (using zipfile), i don't receive anything (However status code is "200 OK"). I replaced the last 2 lines of code with the following:
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()
You read and write both to stringIO
. You should use two separate StringIO
s:
report_name_zip = 'do_something_%(username)s_%(current_date)s.zip'
report_name = "do_something_%(username)s_%(current_date)s.xls"
= StringIO.StringIO()
work_book.save()
= StringIO.StringIO()
with zipfile.ZipFile(, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr(zinfo_or_arcname=report_name, data=.getvalue())
message.attach(report_name_zip, .getvalue())
message.send()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.