Introduction

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>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<br>
<input type="submit" value="Submit">
</form>

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'] = 'your_email@example.com'
msg['To'] = 'recipient_email@example.com'
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login('your_email@example.com', 'your_password')
server.send_message(msg)
server.quit()
return redirect(url_for('thank_you'))
@app.route('/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 'your_email@example.com' and 'recipient_email@example.com' 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__':
app.run()

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


Conclusion

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.