Welcome to a tutorial on how to create a simple online contact form with Python Flask. So you want to create a contact form, but don’t want to deal with Django or all the crazy database stuff? Well, here’s a quick alternative with Flask – Read on!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
- Create your own project folder, e.g.
D:\contact
, unzip the code inside this folder. - Open the terminal (or command line), navigate to your project folder
cd D:\contact
. - As usual, create a virtual environment if you don’t want to mess up your other projects.
virtualenv venv
- Windows –
venv\scripts\activate
- Mac/Linux –
venv/bin/activate
- Get all the packages –
pip install Flask
- Launch!
python 3-server.py
and accesshttp://localhost/
.
EXAMPLE CODE DOWNLOAD
Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
PYTHON CONTACT FORM
All right, let us now get into the details of building a contact form with Python Flask. Not going to explain line-by-line, but here’s a quick walkthrough.
STEP 1) CONTACT FORM
THE HTML
<form id="contactForm" onsubmit="return send();">
<label for="name">Name</label>
<input type="text" name="name" required/>
<label for="email">Email</label>
<input type="email" name="email" required/>
<label for="message">Message</label>
<textarea name="message" required></textarea>
<input type="submit" value="Go!" id="contactGo"/>
</form>
The first step should be self-explanatory. There’s nothing “special” here, this is just a simple HTML contact form. Feel free to change this form and add your own required fields.
THE JAVASCRIPT
// (A) SEND CONTACT FORM
function send () {
// (A1) PREVENT MULTIPLE SUBMIT
document.getElementById("contactGo").disabled = true;
// (A2) COLLECT FORM DATA
let data = new FormData(document.getElementById("contactForm"));
// (A3) SEND!
fetch("/book", { method:"POST", body:data })
.then((res) => {
if (res.status==200) { location.href = "/thank"; }
else { alert("Opps an error has occured."); }
})
.catch((err) => { alert("Opps an error has occured."); });
return false;
}
Next, we have a small bit of Javascript to handle the form submission.
- (A1) Disable the “submit” button to prevent multiple submissions.
- (A2 & A3) Collect the contact form, and send it to the server-side with AJAX fetch post.
STEP 2) THANK YOU PAGE
<h1>Thank You</h1>
<p>We have received your contact request</p>
A dummy “thank you page” on successful contact form submission. Once again, feel free to add your own message here.
STEP 3) SERVER-SIDE FORM HANDLING
INITIALIZE
# (A) INIT
# (A1) LOAD REQUIRED PACKAGES
from flask import Flask, render_template, request, make_response
from werkzeug.datastructures import ImmutableMultiDict
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# (A2) FLASK INIT
app = Flask(__name__)
# app.debug = True
# (B) SETTINGS
HOST_NAME = "localhost"
HOST_PORT = 80
MAIL_FROM = "sys@site.com"
MAIL_TO = "admin@site.com"
MAIL_SUBJECT = "Contact Form"
The first few sections of the server-side are nothing more than loading the required packages and defining the settings. A reminder here to change the settings to your own, especially the email.
ROUTES – HTML PAGES
# (C) ROUTES
# (C1) CONTACT FORM
@app.route("/")
def index():
return render_template("1-contact.html")
# (C2) THANK YOU PAGE
@app.route("/thank")
def thank():
return render_template("2-thank.html")
Don’t think this needs much explanation:
http://localhost/
to serve the contact form1-contact.html
.http://localhost/thank
to serve the “thank you” page2-thank.html
.
CONTACT FORM SUBMISSION
# (C3) SEND CONTACT FORM
@app.route("/send", methods=["POST"])
def foo():
# EMAIL HEADERS
mail = MIMEMultipart("alternative")
mail["Subject"] = MAIL_SUBJECT
mail["From"] = MAIL_FROM
mail["To"] = MAIL_TO
# EMAIL BODY (BOOKING DATA)
data = dict(request.form)
msg = "<html><head></head><body>"
for key, value in data.items():
msg += key + " : " + value + "<br>"
msg += "</body></html>"
mail.attach(MIMEText(msg, "html"))
# SEND MAIL
mailer = smtplib.SMTP("localhost")
mailer.sendmail(MAIL_FROM, MAIL_TO, mail.as_string())
mailer.quit()
# HTTP RESPONSE
res = make_response("OK", 200)
return res
Remember that the Javascript will “send the contact form via AJAX fetch”? This part handles the form submission – Collects the form data, and sends it to the email address that you have specified.
START!
# (D) START!
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
Finally, Captain Obvious at your service – This starts the HTTP web server.
USEFUL BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
EXTRA – MAIL SEND
Please take note that we are using mailer = smtplib.SMTP("localhost")
to send emails. If your server is running Mac/Linux, things should work fine as long as sendmail
is in place. But for Windows users, I will recommend installing Papercut SMTP for easy testing.
P.S. We can also configure smtplib
to use a remote SMTP server. Just read their documentation.
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!