sendgrid / sendgrid-python

The Official Twilio SendGrid Python API Library
https://sendgrid.com
MIT License
1.55k stars 714 forks source link

Attachments always requires FS access #949

Closed mphelp closed 3 years ago

mphelp commented 3 years ago

@thinkingserious and other great package maintainers:

Filename workaround for in memory data?

I have enjoyed using sendgrid but I’ve run into an issue: I want to send maplotlib graph images as attachments WITHOUT writing the images to disk and needing to supply a file name. Your API says file name is required. Is there a way I can keep the images in memory (as in python BytesIO or StringIO packages) and pass its required base64 content to the attachment but mock/fake the file name?

What is the purpose of this?

To avoid FS access for the package I’m developing which depends on sendgrid-python.

mphelp commented 3 years ago

To anyone that's wondering, I have an update:

The following email providers can accept ANY filename for the attachment and receive the email just fine:

The following email providers have some condition:

My solution to avoiding FS writes:

buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
data = buf.read() # returns bytes just like buffered reader IO does

encoded = base64.b64encode(data).decode()
attachment = Attachment()
attachment.file_content = FileContent(encoded)
attachment.file_type = FileType('image/png')
attachment.file_name = FileName('_Graph.png')
message.attachment = attachmen
thinkingserious commented 3 years ago

Hello @mphelp,

Thank you for taking the time to circle back with your solution, we appreciate it!

With best regards,

Elmer