3

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()
Ersain
  • 1,466
  • 1
  • 9
  • 20

1 Answers1

3

You read and write both to stringIO. You should use two separate StringIOs:

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

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

f1 = StringIO.StringIO()
work_book.save(f1)

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

message.attach(report_name_zip, f2.getvalue())
message.send()
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555