Sending mail using flask + blueprint
You should use app_context() like this:
from flask import current_appfrom flask_mail import Message, Mailwith current_app.app_context(): mail = Mail() mail.send(msg)
more info https://flask.palletsprojects.com/en/1.1.x/extensiondev/
The following code is render HTML template for sending mail body including styles or formatted HTML.
from <project-module> import mailtoken = user.get_reset_token()msg = Message('Password Reset Request', sender='<sender-mail>', recipients=[user.email])msg.html = render_template('email_templates/password_reset.html', home_link=url_for('home.index', _external=True), reset_link=url_for( 'account.reset_token', token=token, _external=True), name=user.name, email=user.email)mail.send(msg)
As you mentioned above code. I have been twice initialize Mail object, which is un-necessary.
@main.route('/mail')def sendmail(): receivers = ['<Receiver 1>', '<Receiver 2>'] mail = Mail() with mail.connect() as conn: for receiver in receivers: msg = Message( subject='subject test', recipients=[receiver], html='<h1>Hi~~</h1>') mail.send(msg) return 'ok'
Not a direct answer to your question, but actually I don't think you need to initialize the mail twice.
If you would initialize the mail in app/main/mail.py
, there's no point having mail.init_app(app)
in app/__init__.py
because you never imported it.
Otherwise, in app/main/mail.py
I would do import app.mail
without creating another mail so that you won't have this config issue in the first place.