Search code examples
pythondjangoemailemail-attachmentspython-docx

Create a document using python-docx and send as attachment through django


I have created a document using docx and tried to send as an email attachment without saving the document on the server. Below is my code:

Document = document()
paragraph = document.add_paragraph("Test Content")
f = BytesIO()
document.save(f)
file_list = []
file_list.append(["Test.docx",f, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
email = EmailMessage(subject = 'Test', body = 'Hi', to = ['[email protected]'], attachments = file_list)
email.send()

I am getting the following error:

TypeError: expected bytes-like object, not BytesIO

on the line email.send()

I tried converting BytesIO to StringIO as mentioned here

f = f.read()
f = StringIO(f.decode('UTF-8'))

and then I get the error:

TypeError: expected bytes-like object, not StringIO

I looked at the solution from this, but didn't understand how the document is sent as an attachment.

Any help or pointers is appreciated.

Thanks!


Solution

  • The answer was in the error message.

    Instead of

    file_list.append(["Test.docx",f, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
    

    I did

    file_list.append(["Test.docx", f.getValue(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
    

    Because in my code f is a BytesIO object and f.getValue() returns the contents of the object as bytes.

    Documentation: https://docs.python.org/3/library/io.html#io.BytesIO.getvalue