sendgrid-python: 400 Bad Request When Attaching PDF

I’m trying to email a PDF generated by Weasyprint but receiving 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.

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.

Technical details:

  • sendgrid-python Version: 3.6.0
  • Python Version: 3.5.1

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 15 (6 by maintainers)

Most upvoted comments