代码之家  ›  专栏  ›  技术社区  ›  Jessie

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

  •  2
  • Jessie  · 技术社区  · 8 年前

    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中attach()函数的参数中的attach()。果心邮政

    1 回复  |  直到 8 年前
        1
  •  1
  •   Prakhar Trivedi Ivan    8 年前

    此代码中存在问题:

    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)
    

    文档附件

    您需要用以下代码替换上述代码:

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

    文件的制作不应该是HttpResponse,而是使用