我目前使用python_docx爲了在Python中創建Word文檔。我想要實現的是我需要在Django中創建文檔文件,然後使用django.core.mail將它附加到電子郵件中,而不必將文件保存在服務器上。我試圖創建一個使用這個Word文件(從內也StackOverflow上的回答):創建Word文檔,然後將其附加到電子郵件Django
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), '[email protected]',to=['[email protected]'])
docattachment = generate('Test','CONTENT')
message.attach(docattachment.name,docattachment.read(),docattachment.content_type)
message.send()
我試圖達到甚至可能嗎?
編輯:我基於從所述連接()函數的參數message.attach()的代碼在django.core.mail
當然這是可能的。但是,我沒有看到需要創建一個'HTTPResponse'對象。你有這個錯誤嗎? –
是的。很多,有沒有更短的或不同的方式來做到這一點? – Jessie
我該怎麼做? – Jessie