Written by Sümeyye Sever (notes I took while learning Python)
Make sure you've got the correct smtp address for your email provider
Gmail: smtp.gmail.com
Go to https://myaccount.google.com/
Select Security on the left and scroll down to How you sign in to Google.
Enable 2-Step Verification
Find the section on App Passwords by searching for it
There you can add an App password.
Select give your app a name e.g., Flask Form and click create.
COPY THE PASSWORD - This is the only time you will ever see the password. It is 16 characters with no spaces.
Use this App password in your Python code instead of your normal password.
import os
import smtplib
from flask import Flask, render_template, request
import requests
posts = requests.get("<https://api.npoint.io/c790b4d5cab58020d391>").json()
app = Flask(__name__)
my_email = os.environ["MY_EMAIL"]
my_password = os.environ["MY_PASSWORD"]
@app.route('/')
def get_all_posts():
print(my_email)
return render_template("index.html", all_posts=posts)
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/contact", methods=["POST", "GET"])
def contact():
if request.method == 'POST':
msg = request.form["name"] + "\\n" + request.form["email"] + "\\n" + request.form["phone"] + "\\n" + request.form["message"]
encoded_msg = msg.encode('utf-8')
with smtplib.SMTP("smtp.gmail.com", port=587) as connection:
connection.starttls()
connection.login(user=my_email, password=my_password)
connection.sendmail(from_addr=request.form["email"], to_addrs=my_email, msg=encoded_msg)
print(request.form["name"] + "\\n" + request.form["email"] + "\\n" + request.form["phone"] +
"\\n" + request.form["message"])
return render_template("contact.html", main_h1="Successfully send your msg!")
else:
return render_template("contact.html", main_h1="Contact Me!")
@app.route("/post/<int:index>")
def show_post(index):
requested_post = None
for blog_post in posts:
if blog_post["id"] == index:
requested_post = blog_post
return render_template("post.html", post=requested_post)
if __name__ == "__main__":
app.run(debug=True, port=5001)
my_email = os.environ["MY_EMAIL"]
my_password = os.environ["MY_PASSWORD"]
my_email is your own email address where you want to receive messages from the "Contact Me!" form.
my_password is the 16-character password that you created earlier in your Google account.
@app.route("/contact", methods=["POST", "GET"])
@app.route: This is a Flask route decorator. It binds the /contact URL endpoint to the contact function.methods=["POST", "GET"]: Specifies that this route supports both HTTP POST and GET requests. GET is typically used for displaying the page, and POST is for submitting data.msg = request.form["name"] + "\\n" + request.form["email"] + "\\n" + request.form["phone"] + "\\n" + request.form["message"]
encoded_msg = msg.encode('utf-8')