I have the following code:
Blueprint file snippet:
...
from flask_mail import Message
from app import mail
from os import environ
...
@index_bp.route('/contact', methods=['POST'])
def contact():
form = ContactForm()
if form.validate_on_submit():
print('Form received')
msg = Message('Test', recipients=environ.get('TARGET_MAIL'))
print('msg created')
msg.body = 'Test mail'
print('Body created')
mail.send(msg)
print('Mail sent')
return redirect(url_for('.index'))
Config file:
class Config:
STATIC_FOLDER = 'static'
TEMPLATES_FOLDER = 'templates'
SECRET_KEY = environ.get('SECRET_KEY')
MAIL_SERVER = 'smtp.google.com'
MAIL_PORT = 465
MAIL_USERNAME = environ.get('MAIL_USERNAME')
MAIL_PASSWORD = environ.get('MAIL_PASSWORD')
MAIL_USE_TLS = False
MAIL_USE_SSL = True
MAIL_DEFAULT_SENDER = environ.get('MAIL_USERNAME')
init file:
from flask import Flask
from flask_mail import Mail
mail = Mail()
def init_app():
# Set up core app
app = Flask(__name__)
app.config.from_object('config.Config')
mail.init_app(app)
with app.app_context():
# Import app routes
from .index import routes
# Register blueprints
app.register_blueprint(routes.index_bp)
return app
When I attempt to test the email functionality of the app, the mail.send(...)
part just hands up. It never resolves, effectively not raising any errors but leaving the page loading forever. Most likely it has to do with Gmail, but I have no clue what is missing.
Any help is highly appreciated. Here are the prints the code generates:
Form received
msg created
Body created
proceeds to avoid doing anything else leaving the page loading
** Update **
Here is another snippet I made for the sole purpose of testing Flask Mail with Gmail and still got the same error:
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
app.config['MAIL_SERVER']='smtp.google.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '<new gmail account>@gmail.com'
app.config['MAIL_PASSWORD'] = '<app password>'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
@app.route("/")
def index():
msg = Message('Hello from the other side!', sender = '<new gmail account>@gmail.com', recipients = ['<my gmail address>@gmail.com'])
msg.body = "This is a test email"
mail.send(msg)
return "Message sent!"
Edit:
The error was using smtp.google.com instead of smtp.gmail.com, however, the answer posted here helped a lot as well :).
CodePudding user response:
It because of your Google account, Google recently change some security features that don't let less secure apps to signing in to your account with just username and password, You can use app password in MAIL_PASSWORD configuration instead of your Google account password to solve the problem
in the link below, I answer the same question you can check it