Victor Elias Rodriguez Victor Elias Rodriguez - 7 months ago 27
Python Question

Sending an Email with Form Data via Mailgun and Python

I understand the basics of sending a message via the Mailgun API using Python and requests from my site and all works fine. I would like to attach data from an HTML form using request.forms.get(''), but can't figure out the syntax to make it work. The link below is exactly what I need to do, except in Python instead of PHP.

http://www.formget.com/mailgun-send-email/

How can I send the following form data for example through via Mailgun?

HTML FORM (Parts of it to get the point across)

<form action="/send" method="post">
<input name="name" placeholder="Name">
...
<button> ...


ROUTE (Parts of it to get the point across)

@route('/send', method='POST')
def send_simple_message():
variable_I_need_to_send = request.forms.get('firstname')
...
data={...",
"to": "MyName <myname@gmail.com>",
"subject": "Website Info Request",
"text": "Testing some Mailgun awesomness!",
"html": **variable_I_need_to_send**})
return '''


Thank you

Answer

You can use the requests library:

import requests

@route('/send/<firstname>', method='POST')
def send_simple_message(first_name):
    ...
    data={...",
            "from": "{} <address>".format(first_name),
            "to": "MyName <myname@gmail.com>",
            "subject": "Website Info Request",
            "text": "Testing some Mailgun awesomness!",
            "html": '**I need to include form data here**'})

    requests.post('http://api_url/', data=data)
    return