Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Sendgrid send email with PDF attachment file

I'm trying to attach a PDF file to my email sent with sendgrid.

Here is my code :

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))

from_email = Email("[email protected]")
subject = "subject"
to_email = Email("[email protected]")
content = Content("text/html", email_body)

pdf = open(pdf_path, "rb").read().encode("base64")
attachment = Attachment()
attachment.set_content(pdf)
attachment.set_type("application/pdf")
attachment.set_filename("test.pdf")
attachment.set_disposition("attachment")
attachment.set_content_id(number)

mail = Mail(from_email, subject, to_email, content)
mail.add_attachment(attachment)

response = sg.client.mail.send.post(request_body=mail.get())

print(response.status_code)
print(response.body)
print(response.headers)

But the Sendgrid Python library is throwing an error HTTP Error 400: Bad Request.

What is wrong with my code ?

like image 803
John Avatar asked Nov 17 '16 13:11

John


2 Answers

Straight from the Sendgrid docs:

import urllib.request as urllib
import base64
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition, ContentId)

import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='[email protected]',
    to_emails='[email protected]',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')
file_path = 'example.pdf'
with open(file_path, 'rb') as f:
    data = f.read()
    f.close()
encoded = base64.b64encode(data).decode()
attachment = Attachment()
attachment.file_content = FileContent(encoded)
attachment.file_type = FileType('application/pdf')
attachment.file_name = FileName('test_filename.pdf')
attachment.disposition = Disposition('attachment')
attachment.content_id = ContentId('Example Content ID')
message.attachment = attachment
try:
    sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sendgrid_client.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)
like image 177
John R Perry Avatar answered Sep 20 '22 20:09

John R Perry


I found a solution. I replaced this line :

pdf = open(pdf_path, "rb").read().encode("base64")

By this :

with open(pdf_path, 'rb') as f:
    data = f.read()

encoded = base64.b64encode(data)

Now it works. I can send encoded file in the set_content :

attachment.set_content(encoded)

Note: The answer above works for Sendgrid v2 or lower. For v3 and up use:

encoded = base64.b64encode(data).decode()
like image 31
John Avatar answered Sep 18 '22 20:09

John