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

<pre><code>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' : '&lt;html&gt;&lt;p&gt;{}&lt;/p&gt;&lt;/html&gt;'.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)
</code></pre>

<p>I've found a similar issue <a href="https://github.com/sendgrid/sendgrid-python/issues/205" rel="nofollow">here</a> but the posted solution did not resolve my problem. Thanks.</p>