Jessie
Jessie

Reputation: 393

Create word document and then attach it to email Django

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), '[email protected]',to=['[email protected]'])
    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

Upvotes: 2

Views: 912

Answers (1)

Prakhar Trivedi
Prakhar Trivedi

Reputation: 8526

The problem is in this code :

def sendmail(self, name,email,description,location):
    message = EmailMessage('Custom Mail', 'Name: '+str(name)+'\nEmail: '+str(email)+'\nDescription: '+str(description)+'\nLocation: '+str(location), '[email protected]',to=['[email protected]'])
    docattachment = generate('Test','CONTENT')
    message.attach(docattachment.name,docattachment.read(),docattachment.content_type)
    message.send()

In this line :

message.attach(docattachment.name,docattachment.read(),docattachment.content_type)

docattachment is the response got from generate() fucntion, and docattachment does not have any attribute named : name or read()

You need to replace above code with this:

message.attach("Test.doc",docattachment,'application/vnd.openxmlformats-officedocument.wordprocessingml.document')

And the making of the file, it shouldn't be an HttpResponse and instead use BytesIO to deliver the file.

Upvotes: 1

Related Questions