Thursday, November 28, 2013

SendGrid using Python - a fix to image attachments

For those of you who have been using SendGrid Python API to send emails (there are many advantages to using SendGrid, for example, great analytics, spam protection and the fact that there's a good deal when working with GAE), you might have stumbled upon a problem when trying to send image attachments.

The specification on SendGrid's site show examples of dealing with attachments that are locally hosted (you have to supply a path to the file). But what about sending photos that aren't downloaded to your server?

You could try something like this to supply the actual image content:

message.add_attachment("photo.jpg", urlfetch.fetch(photoURL).content)

However this will yield the following exception:
TypeError: file() argument 1 must be encoded string without NULL bytes, not str
To fix this, you can edit the file in the SendGrid library by following this pull request