DEV Community

BharathKumar (BK) Inbasekaran
BharathKumar (BK) Inbasekaran

Posted on


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()
file_list = []
file_list.append(["Test.docx",f, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
email = EmailMessage(subject = 'Test', body = 'Hi', to = [''], attachments = file_list)

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 = 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.


Top comments (2)

rhymes profile image
rhymes • Edited

I'm not familiar with the library BUT:

BytesIO is basically a buffer of bytes in memory, somewhere your library wants bytes, not the buffer itself, hence the:

TypeError: expected bytes-like object, not BytesIO

In the file_list you're doing this:

file_list.append([filename, f, mime_type])

where f is the BytesIO. What you need is the value contained in it:

file_list.append([filename, f.getvalue(), mime_type])

you can see the documentation for that method here:

BTW you should probably tag this post as #help because... you're asking for help :D

bharathbk profile image
BharathKumar (BK) Inbasekaran

Thank you, your suggestion worked for me. I added the tag too :)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git