flask-mail,shell下成功,pycharm下失败?
shell下挂SS用Gmail成功。pycharm中失败,换qq邮箱开启SMTP后填入授权码依旧失败。
import os
from threading import Thread
from flask import Flask, render_template, session, redirect, url_for
from flask_script import Manager, Shell
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_mail import Mail, Message
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string' #加密秘钥
#使用数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
#邮件服务配置
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.environ.get('xxx@qq.com')
app.config['MAIL_PASSWORD'] = os.environ.get('授权码')
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = 'xxx@qq.com'
app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')
manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
mail = Mail(app)
#数据库里定义两个表
class Role(db.Model):
__tablename__ = 'roles'#定义表名
id = db.Column(db.Integer, primary_key=True)#普通整数,主建
name = db.Column(db.String(64), unique=True)#长字符串,唯一
users = db.relationship('User', backref='role', lazy='dynamic')#关联到主表,lazy为禁止自动查询
def __repr__(self):#调试和测试可用
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))#声明为外键,值为role的ID值
def __repr__(self):
return '<User %r>' % self.username
# 异步mail
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
#收件人地址,主题,正文,关键字参数
def send_email(to, subject, template, **kwargs):
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
#提交文字和表格
class NameForm(Form):
name = StringField('What is your name?', validators=[Required()])#RE确保有文字输入
submit = SubmitField('Submit')
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():#如果数据验证成功则返回True
user = User.query.filter_by(username=form.name.data).first()
if user is None:
user = User(username=form.name.data)
db.session.add(user)
session['known'] = False
if app.config['FLASKY_ADMIN']:
send_email(app.config['FLASKY_ADMIN'], 'New User','mail/new_user', user=user)
else:
session['known'] = True
session['name'] = form.name.data #由浏览器记住cookies
return redirect(url_for('index')) #重定向到index
return render_template('index.html', form=form, name=session.get('name'),known=session.get('known', False)) #render调用JINJIA2模板,session有known就返回布尔值
if __name__ == '__main__':
app.run()
主要是填入邮箱的就MAIL_USERNAME,MAIL_PASSWORD,FLASKY_MAIL_SENDER三个吧?不知道是不是还漏了什么
shell下是非异步的时候成功的,加了异步很奇怪没有收到邮件
大家无视注释。。目前在学习,做个标记免得忘了= =
感谢大神帮忙
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
找到原因了,os.environ.get得去掉,取代的是邮箱的字符串就行了。
亲,我也遇到这个问题了啊,改了还是有问题呀。不太明白这几个邮箱的关系。