简体   繁体   中英

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

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 

This worked for me, but not sure if it's the right way to go about things:

@route('/send', method='POST')
def send_simple_message():
    subject = request.forms.get('name')
    item1 =  request.forms.get('emailaddress')
    item2 =  request.forms.get('phone')
    item3 =  request.forms.get('url')
    item4 =  request.forms.get('about')
    text = item1 + " " + item2 + " " + item3 + " " + item4
    ...
        "to": "Vic <myemail@gmail.com>",
        "subject": subject,
        "html": text})
    return '''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM