I’ve got the basic Mailgun API working with Python and can send emails without any issues. Now I’m trying to figure out how to grab form data using request.forms.get() and include it in the email content but I’m stuck on the proper way to do this.
I found a PHP example that does exactly what I want but need to convert it to Python. Here’s what I’m working with:
@route('/submit', method='POST')
def handle_email():
user_name = request.forms.get('username')
user_email = request.forms.get('email')
# How do I properly include user_name in the email?
email_data = {
"from": "[email protected]",
"to": "[email protected]",
"subject": "New Contact Form",
"text": "Message from website",
"html": # Want to put user_name here
}
What’s the correct syntax to include the form variables in the email body?
Template strings work great for this too. I use string.Template for email content since it handles variable substitution cleanly and won’t break with curly braces in CSS or JavaScript. Here’s how:
Really useful when you’ve got longer templates in separate files. I’ve been using this for contact forms for 3 years now and it scales well as templates get more complex.
You can also use .format() instead of f-strings. Something like “html”: “
Contact Form Submission
Name: {}
Email: {}
”.format(user_name, user_email) works fine. I’ve used this for years in my web apps - it’s reliable. Just validate the form data first before putting it in the email body. Check that fields aren’t empty and sanitize special characters that might break your HTML formatting. Also add the user’s email to the reply-to field so you can respond directly.