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

查看:202
本文介绍了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下是非异步的时候成功的,加了异步很奇怪没有收到邮件
大家无视注释。。目前在学习,做个标记免得忘了= =
感谢大神帮忙

解决方案

找到原因了,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'] = '你的邮箱'

这篇关于flask-mail,shell下成功,pycharm下失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆