2016-11-28 42 views
1

我正在嘗試使用xlsxwriter生成xlsx文件,然後將其作爲電子郵件附件發送。以下是我現在有:Django:TypeError阻止將類似字節的對象附加到電子郵件

def WriteToExcel(project): 
    output = BytesIO() 
    workbook = xlsxwriter.Workbook(output) 

    #putting in data 

    workbook.close() 
    xlsx_data = output.getvalue() 
    # xlsx_data contains the Excel file 
    return xlsx_data 

def project_email (request, project_id): 
    project = Project.objects.get(id = project_id) 
    xlsx_data = WriteToExcel(project) 

    message = EmailMessage("Heading", 'Here is the message.', 'HOST', ['[email protected]']) 

    message.attach_file(xlsx_data) 
    message.send() 

,當我試圖發送電子郵件,我有以下錯誤:

TypeError at /projstatus/1/email

cannot use a string pattern on a bytes-like object

有什麼辦法,我可以出去轉轉呢?像,使xlsx文件非二進制文件,或者如果電子郵件中有一個函數來附加二進制文件?

回答

1

其實我找出了這個問題。你只需要像這樣:

def project_email (request, project_id): 
    project = Project.objects.get(id = project_id) 
    xlsx_data = WriteToExcel(project) 

    message = EmailMessage("Heading", 'Here is the message.', 'HOST', ['[email protected]']) 

    message.attach("Report.xlsx", xlsx_data, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') 
    message.send() 

我會以防萬一其他人離開了這個這裏知道同樣的事情