flask-注册成功发送邮件至邮箱

flask框架内主函数 -app.py

from flask_mail import Mail, Message
from flask import Flask, render_template, request, flash, url_for, redirect, session
from flask_bootstrap import Bootstrap
from forms import MailForm
from datetime import datetime

app = Flask(__name__)
app.config['SECRET_KEY'] = 'westos'
bootstrap = Bootstrap(app)

app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = '2236504154'
app.config['MAIL_PASSWORD'] = 'ytrlrowsjqdwdjhj'


def send_mail(to, subject, template, **kwargs):
    mail = Mail(app)
    # 应用上下文
    with app.app_context():
        msg = Message(subject=subject,
                      sender='[email protected]',
                      recipients=to,
                      # body=render_template(template+'.txt',**kwargs),
                      html=render_template(template + '.html', **kwargs))
        mail.send(msg)


@app.route('/register/', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username', None)
        password = request.form.get('password', None)
        email=request.form.get('email',None)
        for user in users:
            if username == user['username']:
                return render_template('register.html', message='用户%s已经存在' % username)
        else:
            addr=request.remote_addr
            time=str(datetime.today()).split('.')[0]
            users.append(dict(username=username, password=password,email=email))
            #传入的变量在template的html文件中使用
            send_mail(to=[str(email),],subject='注册信息',template='registermes',addr=addr,time=time,username=username)
            flash('用户%s已经注册成功,请登录' % username)
            return redirect(url_for('login'))

    return render_template('register.html')

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

html的基模板

{% extends 'bootstrap/base.html' %}

{% block styles %}
    {{ super() }}
    

{% endblock %}
{% block navbar %}

{% endblock %}
{% block content %}

{% endblock %}

register.html为页面显示

{% extends 'base.html' %}
{% block Title %}
    注册页面
{% endblock %}


{% block content %}

注册 已有帐号 登录

{% if message %}

{{ message }}

{% endif %}
{% endblock %}

flask-注册成功发送邮件至邮箱_第1张图片

发送给邮箱的html文件-registermes.html




    
    Title


{{ username }}用户在 (主机名:{{ addr }}){{ time }} 时间注册成功

flask-注册成功发送邮件至邮箱_第2张图片

你可能感兴趣的:(flask-注册成功发送邮件至邮箱)