创建word文档,然后将其附加到电子邮件Django

时间:2017-09-14 09:15:55

标签: python django email python-docx

我目前正在使用python_docx以便在Python中创建Word文档。我想要实现的是我需要在Django中创建文档文件,然后使用django.core.mail将其附加到电子邮件,而无需将文件保存在服务器上。我尝试使用它创建Word文件(取自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

然后我在这里进行实验,并尝试将回复附加到电子邮件中:

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()

我正在努力实现的目标是什么?

编辑:我根据django.core.mail中attach()函数的参数设置了message.attach()的代码

1 个答案:

答案 0 :(得分:1)

问题在于此代码:

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()

在这一行:

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

docattachment 是从generate()fucntion获得的响应,而 docattachment 没有任何名为的名称:name或read()

您需要将以上代码替换为:

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

在制作文件时,它不应该是HttpResponse,而是使用 BytesIO 来传递文件。