5

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.

Sathya
  • 155
  • 1
  • 5
  • 18
  • Yes, base64 requires a binary object, and an Excel file is a binary object. You can use a [`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO) wrapper to avoid writing the object to disk. For interoperability maybe consider sending as CSV instead, though. – tripleee Feb 08 '19 at 07:07
  • Thanks @tripleee , I have a requirement to provide and excel file and not csv unfortunately. However, I'm not clear how I can use BytesIO to create the bytes-like object. – Sathya Feb 08 '19 at 07:17
  • Possible duplicate of [Write to StringIO object using Pandas Excelwriter?](https://stackoverflow.com/questions/28058563/write-to-stringio-object-using-pandas-excelwriter) – tripleee Feb 08 '19 at 07:20
  • Hi @tripleee I've checked that question, but that solution returns the excel file as a StringIO which is a string. To Base64 encode the file, a byte-like object is needed instead of string. – Sathya Feb 08 '19 at 08:06
  • 1
    The modifications to use BytesIO instead of StringIO should be trivial, I hope. If you can't pull it off, maybe post a new question with details about where exactly you are stuck. – tripleee Feb 08 '19 at 08:07
  • Aha! Sorry, it wasn't so trivial to me. Thanks for your help! – Sathya Feb 08 '19 at 08:53
  • This really works for me! Thanks! https://stackoverflow.com/a/58009916/16650302 – Benjamin CHEN Oct 05 '21 at 07:07

1 Answers1

8

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')
Samkit Jain
  • 1,560
  • 2
  • 16
  • 33