同时给多个邮件地址发送邮件。
app.py
from flask import Flask, render_template, request, redirect, url_for, flash, session
from flask_bootstrap import Bootstrap
from flask_mail import Message, Mail
from forms import RegisterForm, MailForm
users = [
{
'username': 'root',
'password': 'root'
},
]
# 实现用户注册, 用户登录, 用户注销, 用户查看
app = Flask(__name__)
app.config['SECRET_KEY'] = 'westos'
bootstrap = Bootstrap(app)
# 配置发送邮件的相关信息
# 指定邮件服务器的域名或者IP
app.config['MAIL_SERVER'] = 'smtp.qq.com'
# 指定端口, 默认25, 但qq邮箱默认为端口号465或587
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = '731231642'
# 开启qq邮箱设置中POP3/SMTP服务以及IMAP/SMTP服务, 通过短信认证得到密码信息
# 此处输入的是POP3的码
app.config['MAIL_PASSWORD'] = "zqzjbjvkjzvpbcgd"
def send_mail(to, subject, template, **kwargs):
mail = Mail(app)
# app.app_context() : 将之前Flask创建的app作为参数传入AppContext类中
# 用于存储当前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)
# 判断两个文件, 有那一个文件写那一句, 如果两者都写的优先显示html文件
)
mail.send(msg)
@app.route('/mail/', methods=['GET', 'POST'])
def mail():
# 实例化表单
form = MailForm()
if form.validate_on_submit():
# 获取用户提交的数据
toEmails = form.toEmails.data.split(',')
toFilename = form.toFilename.data
try:
send_mail(toEmails, "西部开源邮件测试", toFilename)
except Exception as e:
flash("邮件发送失败, 失败原因: %s!" % (e))
else:
flash("邮件发送成功!")
return redirect(url_for('mail'))
return render_template('send_mail.html',form=form)
send_mail.html
{% extends 'base.html' %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %} 发送邮件 {% endblock %}
{% block content %}
发送邮件测试案例
{{ wtf.quick_form(form) }}
{% endblock %}
base.html
{% extends 'bootstrap/base.html' %}
{% block styles %}
{# 先继承父类的css样式导入 #}
{{ super() }}
{% endblock %}
{% block navbar %}
{#让每个页面都可以获取闪现信息闪现#}
{% for item in get_flashed_messages() %}
{{ item }}
{% endfor %}
{% endblock %}
wtf.html
{% extends 'base.html' %}
{#导入模块, 并重命名为wtf#}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %} wtf测试页面{% endblock %}
{% block content %}
注册-wtf测试
{# 根据后台传递过来的form对象生成对应的html代码 #}
{{ wtf.quick_form(form) }}
{% endblock %}