flask web 编程学习笔记5:E-Mail


Flask 可快速简单的实现E-Mail的功能,可以用于用户注册,找回密码等功能,且邮件内容灵活。
复制下述代码的内容,修改成自己的邮箱和一些配置文件就可以实现简单的邮件发送功能。

'''
    Note5. E-Mail And Example
'''
#
#########################################################################
#
#     E-Mail 由flask-mail提供支持,若不验证,Flask-Mail 会连接localhost 
# 上的端口25,无需验证即可发送电子邮件。
#     安装方法:pip install flask-mail
#
#########################################################################
#
import os
from flask import Flask
#
from flask.ext.mail import Mail, Message
#
from threading import Thread
#
app = Flask(__name__)
mail = Mail(app)
#
# 若配置外部邮箱使用如下方式:
#
app.config['MAIL_SERVER'] = 'xxx.mxhichina.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
#
# windows使用如下方式设置环境变量即可:
# (venv) $ set MAIL_USERNAME=
# (venv) $ set MAIL_PASSWORD=
#
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
#
# Linux使用如下方式设置环境变量即可:
# (venv) $ export MAIL_USERNAME=
# (venv) $ export MAIL_PASSWORD=
#
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
#
# Flask-Mail SMTP服务器的配置:
# |--------------------------------------------------------------------------------
# | 配  置         默认值         说  明
# |--------------------------------------------------------------------------------
# | MAIL_SERVER     localhost   电子邮件服务器的主机名或IP 地址
# | MAIL_PORT       25          电子邮件服务器的端口
# | MAIL_USE_TLS    False       启用传输层安全(Transport Layer Security,TLS)协议
# | MAIL_USE_SSL    False       启用安全套接层(Secure Sockets Layer,SSL)协议
# | MAIL_USERNAME   None        邮件账户的用户名
# | MAIL_PASSWORD   None        邮件账户的密码
# | --------------------------------------------------------------------------------
#
# 
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
#
app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <flasky@example.com>'
# ...
app.config['FLASKY_ADMIN'] = os.environ.get('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)

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)
        
def thr_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
    
    
@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',\ 
                           form=form,\ 
                           name=session.get('name'),\
                           known=session.get('known', False))        

if __name__ == '__main__':
    app.run(debug=True)

版权所有丨如未注明,均为原创,转载请注明转自:https://whonee.net/flask-web-%e7%bc%96%e7%a8%8b%e5%ad%a6%e4%b9%a0%e7%ac%94%e8%ae%b05%ef%bc%9ae-mail.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注