【问题标题】:Django: TypeError preventing attaching a bytes-like object to emailDjango:TypeError 阻止将类似字节的对象附加到电子邮件
【发布时间】:2016-11-28 17:51:06
【问题描述】:

我正在尝试使用 xlsxwriter 生成 xlsx 文件,然后将其作为电子邮件附件发送。这是我现在拥有的:

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', ['SAMPLE@gmail.com'])

    message.attach_file(xlsx_data)
    message.send()

当我尝试发送电子邮件时,出现以下错误:

/projstatus/1/email 处的类型错误

不能在类似字节的对象上使用字符串模式

有什么办法可以绕过它吗?比如,将 xlsx 文件设为非二进制文件,或者电子邮件中是否有附加二进制文件的功能?

【问题讨论】:

    标签: django email django-email


    【解决方案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', ['SAMPLE@gmail.com'])
    
        message.attach("Report.xlsx", xlsx_data, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        message.send()
    

    我会把这个留在这里,以防其他人也想知道同样的事情

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      • 2019-06-05
      • 2014-08-15
      相关资源
      最近更新 更多