Others

Send an E-mail in Python Flask


The following example shows, how to send Email from your Gmail with Flask-Mail in Python Flask

First, we have to install Flask-Mail extension

pip install Flask-Mail

Next, Change following settings in your Gmail and Account

i) Gmail->Settings->Forwarding and POP/IMAP->Enable IMAP

ii) Account->Security->Less secure app Access-> On

Configure the following Settings in Flask-Mail

app.config["DEBUG"]=False
app.config["TESTING"]=False
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]=False
app.config["SECRET_KEY"]="sekret_key"
app.config["MAIL_SERVER"]="smtp.gmail.com'"
app.config["MAIL_PORT"]=465
app.config["MAIL_USE_TLS"]=False
app.config["MAIL_USE_SSL"]=True
app.config["MAIL_DEBUG"]=False
app.config["MAIL_USERNAME"]="your_username@gmail.com"
app.config["MAIL_PASSWORD"]="gmail_password"
app.config["MAIL_DEFAULT_SENDER"]=None
app.config["MAIL_MAX_EMAILS"]=None
app.config["MAIL_SUPPRESS_SEND"]=False
app.config["MAIL_ASCII_ATTACHMENTS"]=False
Example
from flask import Flask,render_template
from flask_mail import Mail,Message
import smtplib

app = Flask(__name__)

app.config.update(
  DEBUG=True,
  #EMAIL SETTINGS
  MAIL_SERVER='smtp.gmail.com',
  MAIL_PORT=465,
  MAIL_USE_SSL=True,
  MAIL_USERNAME = 'from@gmail.com',
  MAIL_PASSWORD = 'password'
)
mail = Mail(app)

@app.route("/")
def home():
  try:
    msg = Message("Message Title Here",
      sender="from@gmail.com",
      recipients=["to@gmail.com"])
    msg.body = "Sample Message Body Here"           
    msg.html = "<h1 style='color:green;'>Sample Message Body Here With HTML and CSS Style</h1>"           
    mail.send(msg)
    return 'Mail Send Successfully'
  except Exception as e:
    print(str(e))
  return ""

if __name__=="__main__":
  app.run(debug=True)

Run the Project:

  1. Run 'app.py' file.
  2. Browse the URL 'localhost:5000'.