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

Create word document and then attach it to email Django

我目前正在使用 python_docx 在 Python 中创建 Word 文档。我想要实现的是,我需要在 Django 中创建文档文件,然后使用 django.core.mail 将其附加到电子邮件,而不必将文件保存在服务器上。我试过使用这个创建 Word 文件(也取自 Whosebug 中的一个答案):

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() 的代码

问题出在这段代码中:

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() 函数得到的响应,而 docattachment 没有任何名为 : name 或 read() 的属性

您需要将上面的代码替换为:

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

以及文件的制作,它不应该是 HttpResponse,而是使用 BytesIO 来传递文件。