Python Flask(五) Email

WEB前端 waitig 724℃ 百度已收录 0评论

欢迎访问地平线上的一匹狼-Python Flask(五)

moudule:Flask_mail
配置参数:

中文:

如果不进行配置,Flask_Mail会自动连接localhost上的端口25

啊……调了一大堆错,总算搞定了QQ的邮件发送…… :sob: :sob: :sob: :sob: :sob: :sob: :sob: :sob:

1.向QQ发送邮件是通过SMTP协议发送的,所以我们需要在QQ邮箱的设置中开启SMTP协议:

2.因为QQ采用的是授权码发送邮件的方式,所以发送邮件时的密码是授权码,需要申请一下(这个授权码会被改变,但我不知道是怎样的条件会改变).如上图的生成授权码.

3.千万不要把TTL写成TLE!!!!!!

4.set MAIL_USERNAME/PASSWORD=*** 这个操作是在cmd界面下直接输入即可,意为将key-value:环境变量-值放在系统内.python取出是依赖os模块os.environ.get('key')取出value的.

5.对于QQ邮箱而言,新生成的msg对象sender需要和你发送到的目标用户一样,否则会出现501错误:发送者与接收者不是同一人.

6.发送的shell大概代码为:

7.AC

Code:

#--*--coding:utf-8--*--
from datetime import datetime
from flask import Flask, render_template,session,redirect,url_for,flash
from flask_script import Manager
from flask_bootstrap import Bootstrap   
from flask_moment import Moment
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy
import os
from flask_mail import Mail

class NameForm(FlaskForm):
    name=StringField('What is your name?',validators=[Required()])
    submit=SubmitField('Submit')

app = Flask(__name__)

#Flask-WTF : secret_key
#app.config dict used to save config message.
app.config['MAIL_SERVER']='smtp.qq.com'
app.config['MAIL_PORT']=587
#app.config['MAIL_USE_TLE']=True
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME']=os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD']=os.environ.get('MAIL_PASSWORD')
app.config['SECRET_KEY']='hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI']=\
    'mysql://root:zwt~19970210@localhost/data'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db=SQLAlchemy(app)

manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
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')

    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'))

    def __repr__(self):
        return '<User %r>' % self.username
@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():
        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
        else:
            session['known']=True
        session['name']=form.name.data
        form.name.data=''
        return redirect(url_for('index'))
    return render_template('index.html',
                           current_time=datetime.utcnow(),form=form,name=session.get('name'),known=session.get('known',False))


@app.route('/user/<name>')
def user(name):
    return render_template('user.html', name=name)


if __name__ == '__main__':
    db.create_all()
    manager.run()

接下来我要试试Gmail..

9.成功,而且好像知道了怎么用自己的一个账号发送给另一个账号的奇技淫巧…recipients参数是目标邮箱.结果如下:
Gmail:
1. 给自己发的结果:

2.给QQ邮箱发的结果:

QQ:
接收到Gmail发送的结果:
Aaron

10.将发送邮件功能集成到页面.
功能=>每次添加新用户发送到邮箱信息:'User {{ username }} has joined.'
主要发送代码如下:

def send_email(to,subject,template,**k):
    msg=Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX']+subject,
        sender=app.config['FLASKY_MAIL_SENDER'],recipients=[to])
    msg.body=render_template(template+'.txt',**k)
    msg.html=render_template(template+'.html',**k)
    mail.send(msg)

调用代码:

@app.route('/',methods=['GET','POST'])
def index():
    form=NameForm()
    if form.validate_on_submit():
        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
        form.name.data=''
        return redirect(url_for('index'))
    return render_template('index.html',
                           current_time=datetime.utcnow(),form=form,name=session.get('name'),known=session.get('known',False))

11.最终结果如下:
添加新用户Aaron Swartz:

12.用异步的方法发送邮件:这样会产生一种无延迟感,用户体验更好.
代码如下:

from threading import Thread

def send_async_email(app,msg):
    with app.app_context():
        mail.send(msg)

def send_email(to,subject,template,**k):
    msg=Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX']+subject,
        sender=app.config['FLASKY_MAIL_SENDER'],recipients=[to])
    msg.body=render_template(template+'.txt',**k)
    msg.html=render_template(template+'.html',**k)
    thr=Thread(target=send_async_email,args=[app,msg])
    thr.start()
    return thr

Done!


本文由【waitig】发表在等英博客
本文固定链接:Python Flask(五) Email
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)