UTF-8 cannot decode ReportLab pdf

I'm having an issue regarding the decoding of pdf generated by reportlab library.

Here is the code calling my function:

print('Rendering Report and Sending Mail')
r = renderTestPDF()
sendTestPDF(r)

This is the code creating the PDF:

def renderTestPDF():

 canvas = Canvas('hello.pdf')
 canvas.drawString(72, 72, "Hello, World")
 content = canvas.getpdfdata()
 return content

This is the code sending the email and where I am getting the error:

def sendtestpdf(report):
# Variables For The Server
 emailhost = ''
 emailport = ''

# Variables For The Email
 systemEmail = ''
 password = ''
 recieveremail = ''

# Configure The Email Message
 message = MIMEMultipart()
 message["Subject"] = 'This is a test for pdf creation and attachment'
 message["From"] = systemEmail
 message["To"] = recieveremail

html = """
    <h1>Your report is here!</h1>
"""

# Turn The Message Into A MIME Object
part1 = MIMEText(html, "html")

**---- I THINK THIS IS WHERE THE ERROR IS LYING -----**
binary_pdf = open(report, "rd")
payload = MIMEBase('application', 'octate-stream', Name="Test.pdf")
payload.set_payload((binary_pdf).read())
encoders.encode_base64(payload)
payload.add_header('Content-Decomposition', 'attachment', filename='Test.pdf')

# Add HTML/plain-text parts to MIMEMultipart message
message.attach(part1)
message.attach(payload)

# Create Secure Connection with Server and Send Email
 context = ssl.create_default_context()
 with smtplib.SMTP_SSL(emailhost, emailport, context=context) as server:
     server.login(systemEmail, password)
     server.sendmail(systemEmail, recieveremail, message.as_string())

and lastly, this is the error I'm getting:

Error

Error Hint

Error Body

UPDATE: (MARKING AS ANSWER)

It seems that the canvas created with ReportLab NEEDS to be saved as a .pdf before attempting to read it...

For the reasons of my application, I do not want/need the pdf to be saved anywhere.

A workaround for this is temporarily saving the pdf to the root dir, then opening it from the root dir, attaching it to the email, sending the email and then deleting it from the root dir.

I can't confirm how effective or safe this is, but will look more into it now that I have a working solution.

Back to Top