Skip to main content
 首页 » 编程设计

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

2025年02月15日33mayingbao

我目前正在使用 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() 的代码

请您参考如下方法:

问题出在这段代码中:

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 来传递文件。