BloodViolet
BloodViolet

Reputation: 67

E-Mail attachment using Sendgird

Basically I want my code to send a E-Mail with a attachment (in this case epub).

Right now I use the sendgrid library for sending mails and to send the attachment to sendgrid, it needs to be base64 encoded and send via post to the sendgrid server.

But since json doesn't support byte type I have to convert the my encoded file to a string. I tried for a long time but have no clue what I do wrong, but I'm fairly certain it has to do with the base64 encoded string.

My code atm looks kind of like this:

#Encoding file
with open(filename, 'rb') as f:
    encoded = base64.b64encode(f.read())

attachment = Attachment()

#Is this done correctly?
attachment.content = str(encoded)

attachment.type = "application/epub+zip"
attachment.filename = filename

email = Mail(from_email, subject, to_email, content)
email.add_attachment(attachment)
response = sg.client.mail.send.post(request_body=email.get())

Can someone help?

Upvotes: 0

Views: 2695

Answers (1)

Hiren patel
Hiren patel

Reputation: 971

The documentation for sending e-mails doesn't seem to work when using Python 3. I was also facing this problem. then I found this example here

Replace this line attachment.content = str(encoded) with attachment.content = encoded.decode()

Upvotes: 2

Related Questions