flask-mail,shell下成功,pycharm下失败?

发布于 2022-09-04 11:33:47 字数 4035 浏览 12 评论 0

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤星 2022-09-11 11:33:47

找到原因了,os.environ.get得去掉,取代的是邮箱的字符串就行了。

app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = '邮箱@qq.com'
app.config['MAIL_PASSWORD'] = '授权码'

app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = '你的邮箱'
app.config['FLASKY_ADMIN'] = '你的邮箱'
世界等同你 2022-09-11 11:33:47

亲,我也遇到这个问题了啊,改了还是有问题呀。不太明白这几个邮箱的关系。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文