Create word document and then attach it to email Django

我怕爱的太早我们不能终老 提交于 2019-12-11 02:50:47

问题


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


回答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.



来源:https://stackoverflow.com/questions/46215083/create-word-document-and-then-attach-it-to-email-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!