TypeError : expected bytes-like object, not HttpResponse

i am trying to send an email with pdf file attached. But I have an error when sending the email in my project django

utils.py

from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template

from xhtml2pdf import pisa

def render_to_pdf(template_src, context_dict={}):
  template = get_template(template_src)
  html  = template.render(context_dict)
  result = BytesIO()
  pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result)
  if not pdf.err:
    return HttpResponse(result.getvalue(),
    content_type='application/pdf')
    return None

views.py

def sendMail(request):
    ""
    pdf = render_to_pdf('cart/commande.html',context)
    subject, from_email, to = 'Message with pièce joint : N° 0001', 
    'aab@gmail.com', 
    'too@gmail.com'
    text_content = 'hello'
    html_content = '<p>hello, .</p>'
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.attach('commande_pdf',pdf,'application/pdf')
    msg.send()
    return render(request,'cart/succes.html')

the error points to this line msg.send

Noted the generation of the pdf file is OK, it must be attached to the email

utils.py

It just needed in the utils.py file replace the return with :

replace : return HttpResponse(result.getvalue(), content_type='application/pdf')

by

return result.getvalue()
Back to Top