Attaching StringIO Data to a Mailgun Message

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. Added a name attribute to the StringIO class does the trick:

class NamedStringIO(StringIO):
    name = ''

    def __init__(self, data, name=None):
        if 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():
        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>"})

Recent Posts

Simple OS X XKCD client with Automator
Attaching StringIO Data to a Mailgun Message
A Picture is worth how many words? Part 1
Handy Sale Advertisement Guide.
Black Friday.
Theme Uploaded


python life code boring posts