[Answered ]-'bytes' object has no attribute 'encode' in EmailMessage

1👍

The problem is that you’re sending a PDF file object as the message body:

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 attempts to encode the body with the utf-8 codec, but the body is a PDF file object, which is bytes, and bytes doesn’t provide an encode method only a decode method. The correct way to add a PDF to an email is to attach it as you’ve done later in your code. Now, if you want the email body to be the text of the PDF file, get the text in a str and pass it as the body kwarg.

Leave a comment