【问题标题】:'bytes' object has no attribute 'encode' in EmailMessage“字节”对象在 EmailMessage 中没有属性“编码”
【发布时间】:2021-03-20 05:55:47
【问题描述】:

我正在尝试在 Django 中制作一个应用程序,它接受来自用户的信息并通过电子邮件将 HTML 模板作为 pdf 发送给用户。但我收到了这个错误 'bytes' 对象没有属性 'encode'

这是我对电子邮件的看法

def email(request, serial_no):
    user = get_object_or_404(Student, pk=serial_no)
    # roll_no = {'roll': str(user['roll_no'])}
    html = render_to_string('card.html',
                            {'user': user})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename={}'.format(user.roll_no + '.pdf')
    pdf = weasyprint.HTML(string=html, base_url='').write_pdf(
        stylesheets=[weasyprint.CSS(string='body { font-family: serif}')])
    to_emails = [str(user.roll_no) + '@gmail.com']
    subject = "Certificate from Nami Montana"
    email = EmailMessage(subject, body=pdf, from_email='SSC', to=to_emails)
    email.attach("{}".format(user.roll_no) + '.pdf', pdf, "application/pdf")
    email.content_subtype = "pdf"  # Main content is now text/html
    email.encoding = 'utf-8'
    email.send()
    return HttpResponseRedirect(reverse('id_card:submit'))

这是错误

Traceback (most recent call last):
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Dell\Documents\GitHub\SSC-Website\id_card\views.py", line 49, in email
    email.send()
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\message.py", line 284, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\backends\console.py", line 34, in send_messages
    self.write_message(message)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\backends\console.py", line 17, in write_message
    msg = message.message()
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\message.py", line 246, in message
    msg = SafeMIMEText(self.body, self.content_subtype, encoding)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\message.py", line 159, in __init__
    MIMEText.__init__(self, _text, _subtype=_subtype, _charset=_charset)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\email\mime\text.py", line 42, in __init__
    self.set_payload(_text, _charset)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\message.py", line 167, in set_payload
    has_long_lines = any(
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\message.py", line 168, in <genexpr>
    len(line.encode()) > RFC5322_EMAIL_LINE_LENGTH_LIMIT
AttributeError: 'bytes' object has no attribute 'encode'

提前致谢

【问题讨论】:

  • 请发布整个堆栈跟踪
  • 您对str(Unicode 字符串)进行编码。你解码bytes(字节串)。 line 是一个字节串,所以不能编码。无法分辨代码中的大多数类型,因为它不完整。创建minimal reproducible example

标签: python django encoding utf-8 attributeerror


【解决方案1】:

问题在于您将 PDF 文件对象作为消息正文发送:

pdf = weasyprint.HTML(string=html, base_url='').write_pdf(
        stylesheets=[weasyprint.CSS(string='body { font-family: serif}')])
email = EmailMessage(subject, body=pdf, from_email='SSC', to=to_emails)

EmailMessage 尝试使用 utf-8 编解码器对body 进行编码,但正文是一个 PDF 文件对象,即bytes,而bytes 没有提供encode 方法,只有一个decode 方法。将 PDF 添加到电子邮件的正确方法是按照您稍后在代码中所做的那样附加它。现在,如果您希望电子邮件正文成为 PDF 文件的文本,请获取 str 中的文本并将其作为 body kwarg 传递。

【讨论】:

  • 谢谢。你能再帮我解决一个问题吗?当我尝试使用 Adob​​e Reader 打开 pdf 时,它显示“处理页面时出错。阅读此文档时出现问题 (135)”。
  • @BibekPaul,文件中可能有一些不受支持的字符(Adobe Reader 提供)。尝试使用 Chrome 或 foxitsoftware.com/pdf-reader 打开它。
  • 如果我给你看 html 代码,你能指出哪些字符是那些字符吗
  • @BibekPaul,不,我不知道所有不受支持的 utf-8 字符,我只知道这是过去的问题。我最好的建议是在支持字符的查看器中查看 PDF,并怀疑奇怪的稀有字符。
猜你喜欢
  • 2016-11-09
  • 2019-02-02
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
  • 2016-01-27
相关资源
最近更新 更多