Reputation: 185
I need to use SendGrid to send emails from my application. I've made the transactional templates in sendgrid and now need to attach excel to the emails that go out.
According to their Web API V3 documentation, the attachment can be added by encoding the file in Base64. I've tried searching for solutions to encode the file in Base64, but can't find a solution to it. From what I understand of the base64 package, it can only encode bytes-like objects.
So, do I need to read the excel file into a byte-like object before I can encode it? Is there a package that will do this for me magically?
My application currently generates the excel file by using the pandas to_excel() method.
Thanks in advance :)
[Update 1] I've checked this question if mine could be a duplicate, however, that question returns the file as a String, but to do the Base64 encoding, I need a byte-like object to encode my excel file.
I did try the solution provided in that question but it did not work because the final return was a string.
Upvotes: 6
Views: 18505
Reputation: 1748
To encode an Excel file to base64, try this
import base64
data = open(excel_path, 'rb').read()
base64_encoded = base64.b64encode(data).decode('UTF-8')
Upvotes: 11