Error when trying to send emails with Flask and Gmail

Viewed 302

I'm trying to use Gmail to send emails from my flask application but I'm getting this error message: smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required.

I've reviewed all related questions and here are the solutions I've tried:

  1. Turn on "Less secure app access"
  2. Try to sign in with "App password"
  3. I'm already saving my email credentials as environment variables

Here is my code:

from flask import Flask, render_template, redirect, request
from flask_mail import Mail, Message

app = Flask(__name__)

app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 587
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USER"] = os.getenv("MAIL_USERNAME")
app.config["MAIL_DEFAULT_SENDER"] = os.getenv("MAIL_USERNAME")
app.config["MAIL_PASSWORD"] = os.getenv("MAIL_PASSWORD")
mail = Mail(app)

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        recipient = request.form.get("email")
        msg = Message("Welcome on board!", recipients=[recipient])
        mail.send(msg)
    elif request.method == "GET":
        return render_template("greetings.html")
1 Answers

For google smtp try:

MAIL_PORT = 465
MAIL_USE_SSL = True
Related