Search code examples
pythonbottlemailgun

Sending User Uploaded Attachments with Mailgun and Bottle


I am following MailGun's documentation for attaching a file, but all the examples have a file already selected. How can I send an attachment uploaded by the user?

The code works fine with sending messages, but when I added this part ...

files=[("attachment", open(request.files.data.file)),],

I get this error:

TypeError: invalid file: <_io.BufferedRandom name=19>

HTML Form

<form action="/subr" method="post" enctype="multipart/form-data">
<input id="main" name="em" type="email"  placeholder="E-MAIL" required><br>
<textarea id="main" name="about"  placeholder="DESCRIBE THE FILE"></textarea><br>
<input id="main" type="file" name="data" required>
 <button type="submit">SUBMIT FILE</button>
</form>

Bottle Route:

@route('/subr', method='POST')
def submitr():
    subject = "File Submission"
    item1 =  request.forms.get('em')
    item2 =  request.forms.get('about')
    text = str(item1) + " " + str(item2)
    requests.post("https://api.mailgun.net...",
    auth=("api", "key-4..."),
    files=[("attachment", open(request.files.data.file)),],
    data={"from": "Mailgun Sandbox <[email protected]>",
        "to": "Me <[email protected]>",
        "subject": subject,
        "html": text})
    return "<p>Success</p>"

Any help is appreciated.


Solution

  • request.files.data.file is already opened; just read from it. Does this work?

    files=[("attachment", request.files.data.file)],