Adding a contact form to your Flask application allows users to get in touch with you, provide feedback, or make inquiries. In this guide, we'll walk you through the process of creating and integrating a contact form in your Flask app. You'll learn how to set up the form, process submissions, and send email notifications.

Step 1: Setting Up Your Flask Application

Before you can add a contact form, make sure you have a Flask application. If not, you can create a basic Flask app like this:

from flask import Flask, render_template, request
app = Flask(__name)

Step 2: Creating a Contact Form

Create a form using HTML and add it to your template. Here's an example of a simple contact form:

<form method="POST" action="/contact">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<input type="submit" value="Submit">

Create a route in your Flask app to render the form and handle submissions.

Step 3: Handling Form Submissions

Create a route to handle the form submissions and send email notifications. Here's an example route that processes the contact form:

from flask import Flask, render_template, request, redirect, url_for
import smtplib
from email.message import EmailMessage
app = Flask(__name)
@app.route('/contact', methods=['POST'])
def contact():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
message = request.form['message']
# Send an email
msg = EmailMessage()
msg.set_content(f"Name: {name}\nEmail: {email}\nMessage: {message}")
msg['Subject'] = 'Contact Form Submission'
msg['From'] = ''
msg['To'] = ''
server = smtplib.SMTP('', 587)
server.login('', 'your_password')
return redirect(url_for('thank_you'))
def thank_you():
return "Thank you for your message!"

In this example, the route processes the form data and sends an email notification. You should replace '' and '' with your actual email addresses and configure your SMTP server and credentials.

Step 4: Running Your Application

As usual, run your Flask application with the following code at the end of your script:

if __name__ == '__main__':

Now, you can run your application with the command python and access the contact form to send messages.


Adding a contact form to your Flask application allows users to easily get in touch with you. By following these steps, you can set up a simple contact form, process user submissions, and send email notifications to receive and respond to user messages.