2017-09-14 42 views
1

我目前使用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

+0

當然這是可能的。但是,我沒有看到需要創建一個'HTTPResponse'對象。你有這個錯誤嗎? –

+0

是的。很多,有沒有更短的或不同的方式來做到這一點? – Jessie

+0

我該怎麼做? – Jessie

回答

1

的問題是在這樣的代碼:

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(docattachment.name,docattachment.read(),docattachment.content_type) 

docattachment是響應從生成了()fucn重刑,並docattachment沒有名爲任何屬性)

名稱或讀(你需要它來取代上面的代碼:

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

和文件的製作,它不應該是HttpResponse,而是使用BytesIO來傳遞文件。

+0

嗯,這不是你的答案,它使它的工作,但它確實幫助我搞清楚如何。謝謝。 – Jessie

+0

如果我應該誠實地處於虧損狀態,因爲還有其他因素可能會導致您的答案無法正常工作,因爲您應該指出它不應該是HttpResponse而是使用BytesIO。我給它一個upvote,但如果你編輯它,是的。我會接受它:) – Jessie

相關問題