2

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

Jessie
  • 363
  • 2
  • 6
  • 20

1 Answers1

1

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), 'test@gmail.com',to=['testreceiver@gmail.com'])
    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.

Prakhar Trivedi
  • 8,218
  • 3
  • 28
  • 35
  • Well, it wasn't exactly your answer that made it work, but it did help me figuring out how. Thanks. – Jessie Sep 15 '17 at 06:18
  • I'm honestly at a loss if I should since there are other factors as to why your answer wouldn't work as is since you should've pointed out the it shouldn't be an HttpResponse and instead use BytesIO. I'm giving it an upvote but if you edit it, yeah. I'll accept it :) – Jessie Sep 15 '17 at 07:33