1

I have created a workbook using xlwt, now I was wondering if I could send an email using this workbook, but a without saving the workbook on disk. I am unable to do a proper implementation where I could send it as an attachment without saving it on disk temporarily. Here is the code for email as an attachment.

file_name = "temp_file_location.xlsx"
book = xlwt.Workbook()
sheet = book.add_sheet("XYZ")
book.save(file_name)

message = EmailMessage(subject="Subject", body="body",
             from_email="random@gmail.com", 
             to=email_list)
message.attach_file(file_name)
message.send()

There is a similar question here: How to send an email with attachment?

But no solution, and I am unable to send email without saving it on disk temporarily.

Any Ideas?

Community
  • 1
  • 1
Namit Singal
  • 1,506
  • 12
  • 26

2 Answers2

6

You can write your workbook in memory using StringIO:

import StringIO
f = StringIO.StringIO() # create a file-like object 
book = xlwt.Workbook()
sheet = book.add_sheet("XYZ")
book.save(f)

message = EmailMessage(subject="Subject", body="body",
         from_email="random@gmail.com", 
         to=email_list)
message.attach('filename.xlsx', f.getvalue(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") #get the stream and set the correct mimetype
message.send()

taken from xlwt write excel sheet on the fly

Community
  • 1
  • 1
abriemme
  • 135
  • 6
0

StringIO did not work with me (Python 3.9.17 & Django 3.2.13), I had to use BytesIO:

import io
from django.core.mail import EmailMessage

mail = EmailMessage(subject="my test mail",
                    to=['you@example.com'],
                    body="this is my message")

wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('TEST')
# add stuff to worksheet...

with io.BytesIO() as xls:
    wb.save(xls)
    mail.attach(filename="test-attach.xls", 
                content=xls.getvalue(), 
                mimetype="application/ms-excel")

mail.send(fail_silently=False)
rubbish
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 03 '23 at 08:15