DAY5-Flask

使用Flask-Mail提供电子邮件支持

pip install flask-mail

Flask-Mail连接到简单邮件传输协议(SMTP)服务器,并把邮件交给这个服务器发送。如果不进行配置,Flask-Mail会连接localhost上的端口25,无需验证即可发送电子邮件。

Flask-Mail SMTP服务器的配置
配置 默认值 说明
MAIL_SERVER localhost 电子邮件服务器的主机名或IP地址
MAIL_PORT 25 电子邮件服务器的端口
MAIL_USE_TLS False 启动传输层安全(TLS)协议
MAIL_USE_SSL False 启动安全套接层(SSL)协议
MAIL_USERNAME None 邮件账户的用户名
MAIL_PASSWORD None 邮件账户的密码
配置Flask-Mail使用163Mail
from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.163.com'  # 电子邮件服务器的主机名或IP地址
app.config['MAIL_PORT'] = '25'  # 电子邮件服务器的端口
app.config['MAIL_USE_TLS'] = True  # 启用传输层安全
app.config['MAIL_USERNAME'] = ''xxxxxxx  # 邮件账户用户名
app.config['MAIL_PASSWORD'] = 'xxxxxxx'  # 邮件账户的密码

mail = Mail(app)


@app.route('/')
def index():
    msg = Message('主题',sender= ''xxxxxxx',recipients=['yyyyyyyyyyyyy'])
    msg.body = '文本 body'
    msg.html = 'HTML body'
    mail.send(msg)

    return '

邮件发送成功

' if __name__ == '__main__': app.run(debug=True)
电子邮件支持
from flask_mail import Mail, Message

app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin '

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)
    mail.send(msg)

两个程序特定配置项,分别定义邮件主题的前缀和发件人地址。send_email函数的参数分别为收件人地址、主题、渲染邮件正文的模板和关键字参数列表。指定模板时不能包含扩展名,这样才能使用两个模板分别渲染纯文本正文和富文本正文。

电子邮件示例
app.config['FLASKT_ADMIN'] = 'yyyyyyy'

@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['FLASKT_ADMIN']:
                send_email(app.config['FLASKT_ADMIN'], 'New User', 'mail/new_user', user=user)
            # flash('Looks like you have changed your name!')
        else:
            session['known'] = True
        session['name'] = form.name.data
        form.name.data = ''
        return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'), known=session.get('known', False))
异步发送电子邮件
from threading import Thread

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

在不同线程中执行mail.send()函数时,程序上下文使用app.app_context()人工创建。

你可能感兴趣的:(DAY5-Flask)