Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 4, 2023 06:18
Show Gist options
  • Save code-boxx/d05f593b737a71339a27220ccf645208 to your computer and use it in GitHub Desktop.
Save code-boxx/d05f593b737a71339a27220ccf645208 to your computer and use it in GitHub Desktop.
Python Flask Contact Form

SIMPLE PYTHON FLASK CONTACT FORM

https://code-boxx.com/contact-form-python-flask/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create a static folder, move S1B_contact.js and S1C_contact.css inside.
    • Create a templates folder, move S1A_contact.html and S2_thank.html inside.
    • Create a virtual environment - virtualenv venv
    • Activate the virtual environment - venv\scripts\activate (Windows) venv/bin/activate (Mac/Linux)
    • Install Flask pip install flask
    • Start the server python S3_server.py
  2. Access http://localhost in your browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<!DOCTYPE html>
<html>
<head>
<title>JS Contact</title>
<meta charset="utf-8">
<script async src="static/S1B_contact.js"></script>
<link rel="stylesheet" href="static/S1C_contact.css">
</head>
<body>
<!-- (A) CONTACT FORM -->
<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>
</body>
</html>
// (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("/send", { method:"POST", body:data })
.then(res => {
if (res.status==200) { location.href = "/thank"; }
else {
console.log(res);
alert("Opps an error has occured.");
}
})
.catch(err => {
console.error(err);
alert("Opps an error has occured.");
});
return false;
}
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
#contactForm {
padding: 20px;
max-width: 500px;
background: #f7f7f7;
}
#contactForm input, #contactForm label, #contactForm textarea {
display: block;
width: 100%;
}
#contactForm textarea { height: 150px; }
#contactForm input, #contactForm textarea { padding: 10px; }
#contactForm label { padding: 10px 0; }
#contactForm input[type="submit"] {
margin-top: 20px;
border: 0;
color: #fff;
background: #cb1111;
cursor: pointer;
}
#contactForm input[type="submit"]:disabled { background: #424242; }
<!DOCTYPE html>
<html>
<head>
<title>JS Contact Form</title>
<meta charset="utf-8">
</head>
<body>
<h1>Thank You</h1>
<p>We have received your contact request</p>
</body>
</html>
# (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"
# (C) ROUTES
# (C1) CONTACT FORM
@app.route("/")
def index():
return render_template("S1A_contact.html")
# (C2) THANK YOU PAGE
@app.route("/thank")
def thank():
return render_template("S2_thank.html")
# (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 (CONTACT 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
# (D) START!
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
md templates
md static
move S2_thank.html templates
move S1A_contact.html templates
move S1B_contact.js static
move S1C_contact.css static
virtualenv venv
call venv\Scripts\activate
pip install flask
python S3_server.py
mkdir -m 777 templates
mkdir -m 777 static
mv ./S2_thank.html ./templates
mv ./S1A_contact.html ./templates
mv ./S1B_contact.js ./static
mv ./S1C_contact.css ./static
virtualenv venv
source "venv/bin/activate"
pip install flask
python S3_server.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment