2

I'm trying to email a PDF generated by Weasyprint with Sendgrid. The Sendgrid Python library is throwing an error HTTP Error 400: Bad Request which while not very descriptive I believe is due to an issue with the encoding of the attachment (Sendgrid wants attachments in base64).

html_page, css_page = generatePDF(url) # Generates HTML and CSS from URL
pdf = html_page.write_pdf(stylesheets=css_page) # Compiles PDF from HTML and CSS as bytes string

pdf = base64.b64encode(pdf).decode() # Base64 encodes PDF

data = {
    'personalizations' : [
        {
            'to' : [
                {
                    'email' : data['to']
                }
            ],
            'subject' : data['subject']
        }
    ],
    'from' : {
        'email' : data['from']
    },
    'content' : [
        {
            'type' : 'text/plain',
            'value' : data['text']
        },
        {
            'type' : 'text/html',
            'value' : '<html><p>{}</p></html>'.format(data['html'])
        }
    ],
    'reply_to' : {
        'name' : '{}'.format(sender_name),
        'email' : '{}'.format(sender_email)
    },
    'attachments' : {
        'content' : pdf,
        'filename' : data['filename'],
        'type' : 'application/pdf'
    }
}

sg = sendgrid.SendGridAPIClient(apikey = SENDGRID_API_SECRET)
rq = sg.client.mail.send.post(request_body = data)

I've found a similar issue here but the posted solution did not resolve my problem. Thanks.

apardes
  • 4,272
  • 7
  • 40
  • 66
  • I had the same problem about the encoding pdf file in base64. I found a solution. I made a post here -> http://stackoverflow.com/a/40658111/2519631 if it can help you. – John Nov 17 '16 at 15:01

0 Answers0