Flask Mail不发送电子邮件

时间:2019-05-31 22:12:27

标签: python flask flask-mail

我正在尝试使用flask-mail发送重置密码的电子邮件。该代码执行没有错误,但是我没有收到任何电子邮件。

我尝试了以下操作:

  1. 将这些行添加到 init .py文件中的app.config中:
app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_DEBUG'] = True
app.config['DEBUG'] = True
app.config['MAIL_FAIL_SILENTLY'] = False 
app.config['TESTING'] = False
  1. 在Gmail中更改(减少对应用程序的安全访问)设置。

下面是我的代码的几行:

init .py文件中:

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy 
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True 
app.config['MAIL_USERNAME'] = os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_DEBUG'] = True
app.config['DEBUG'] = True
app.config['MAIL_FAIL_SILENTLY'] = False 
app.config['TESTING'] = False
mail = Mail(app)

在routes.py文件中:

def send_reset_email(user):
    token = user.get_reset_token()
    msg = Message(subject='Password Reset Request', sender='noreply@demo.com', recipients=[user.email])

    msg.body = f''' To reset your password, visit the following link!:
{url_for('reset_token', token=token, _external=True)}

If you did not make this request then simply ignore this email and no changes will be made
'''

@app.route("/reset_password", methods=['GET', 'POST'])
def reset_request():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash('An email has been sent with instructions to reset your password.', 'info')
        return redirect(url_for('login'))
    return render_template('reset_request.html', title='Reset Password', form=form)

我希望收到重设的电子邮件,但我没有收到,并且它默默地失败了。

2 个答案:

答案 0 :(得分:0)

您将需要致电mail.send(msg)

答案 1 :(得分:0)

1)在添加到 init 文件

app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USERNAME'] = os.environ.get('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
app.config['MAIL_USE_TLS'] = False 
app.config['MAIL_USE_TLS'] = True 

2)在 route.py 文件

需要:

mail.send(msg)