Trenton Broughton danger: high entropy

Attaching StringIO Data to a Mailgun Message

code python

Recently I started using Mailgun for our outgoing messages. They have a very nice API, and take a lot of the heavy lifting out of creating multipart messages.

If you are using requests (or treq) to send the messages through their REST API, however, you may have noticed that you must specify “attachment” as the key, and an open file handle as the value. This works great if you are sending files from the filesystem, but if you need to send generated or in memory data as a file attachment, it just doesn’t work. Adding a name attribute to the StringIO class does the trick:


class NamedStringIO(StringIO):
    name = ''

    def __init__(self, data, name=None):
        if name:
            self.name = name
        StringIO.__init__(self, data)

Now using their example will work:

from paste.util import MultiDict

good = NamedStringIO("This is some good data", "good.txt")
more = NamedStringIO("This is some more good data", "more.txt")

def send_complex_message():
    return requests.post(
        "https://api.mailgun.net/v2/samples.mailgun.org/messages",
        auth=("api", "key-PUT_YER_KEY_HERE"),
        files=MultiDict([("attachment", good),
                         ("attachment", more)]),
        data={"from": "Excited User <[email protected]>",
              "to": "[email protected]",
              "cc": "[email protected]",
              "bcc": "[email protected]",
              "subject": "Hello",
              "text": "Testing some Mailgun awesomness!",
              "html": "<html>HTML version of the body</html>"})