Encode CSV file for Sendgrid Mailing API
I am trying to create a client reporting engine using R / Python and the Sendgrid mailing API. I can send emails, but the last thing I need to do is attach the client's CSV report.
I tried several approaches including base64 encoding the file and writing the string to disk from R to python, but no luck. However, it looks like I am stuck with this error:
TypeError: Object of type 'bytes' is not JSON serializable
My code:
with open('raw/test-report.csv', 'rb') as fd:
b64data = base64.b64encode(fd.read())
attachment = Attachment()
attachment.content = b64data
attachment.filename = "your-lead-report.csv"
mail.add_attachment(attachment)
What's confusing is that if I just replace b64data
with the string
attachment.content = 'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12'
an email is sent with the attachment.
For reference, I used:
https://github.com/sendgrid/sendgrid-python
and
and there were no problems until this last step in my project.
Any help would be greatly appreciated. It's worth noting that my strength is in R
, but I can usually hack things in python
using the internet.
source to share
You need to convert b64data
to a regular string before assigning attachment.content
. Sendgrid creates a JSON payload that it sends in requests, so it doesn't know how to serialize the value assigned attachment.content
, which in this case is bytestring
.
str(b64data,'utf-8')
Links:
source to share