I'm currently using python_docx in order to create Word Documents in Python. What I'm trying to achieve is that I need to create Document File in Django and then attach it to an email using django.core.mail without having to save the file on the server. I've tried creating the Word File using this (taken from an answer also within StackOverflow):
def generate(self, title, content):
document = Document()
docx_title=title
document.add_paragraph(content)
f = BytesIO()
document.save(f)
length = f.tell()
f.seek(0)
response = HttpResponse(
f.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
)
response['Content-Disposition'] = 'attachment; filename=' + docx_title
response['Content-Length'] = length
return response
And then here is where I experimented and tried to attach the response to the email:
def sendmail(self, name,email,description,location):
message = EmailMessage('Custom Mail', 'Name: '+str(name)+'\nEmail: '+str(email)+'\nDescription: '+str(description)+'\nLocation: '+str(location), 'test@gmail.com',to=['testreceiver@gmail.com'])
docattachment = generate('Test','CONTENT')
message.attach(docattachment.name,docattachment.read(),docattachment.content_type)
message.send()
Is what I'm trying to achieve even possible?
EDIT: I based the code of message.attach() from the parameters of the attach() function in django.core.mail