电子邮件xlsx附件Django

时间:2016-05-20 09:30:43

标签: django python-2.7 email-attachments xlsxwriter

def email_page(request):
    t = get_template('email.html')
    email = EmailMessage('Hello', 'Test<br>break', 'email@hotmail.com',['email@hotmail.com'])
    email.content_subtype = "html"

    workbook = xl.Workbook('ex.xlsx')
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, 'Total')
    workbook.close()
    email.attach("ex.xlsx", workbook, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    email.send()
    return HttpResponse(t.render(Context({})), status=200)
  

我在email.attach专栏上尝试了以下更改:

  • workbook.read() - read不是工作簿workbook.getvalue()的属性

  • workbook.getvalue() - getvalue不是工作簿的属性

  • 工作簿 - TypeError:&#39;文件&#39; object不支持索引

1 个答案:

答案 0 :(得分:2)

def email_page(request):
    t = get_template('email.html')
    email = EmailMessage('Hello', 'Test<br>break', 'email@hotmail.com',['email@hotmail.com'])
    email.content_subtype = "html"
    f = StringIO.StringIO() # create a file-like object 
    workbook = xl.Workbook(f)
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, 'Total')
    workbook.close()
    email.attach("b.xlsx", f.getvalue(), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    email.send()
    return HttpResponse(t.render(Context({})), status=200)

这样我们仍然可以使用xlsx writer来制作文件。