安装
pip install flask-mail
作用
发送邮件的扩展库
实例
from flask import Flask,render_template
from flask_script import manager
from flask_mail import Mail,Message
import time
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_USERNAME'] = '689668@qq.com'
# 授权码或者密码
app.config['MAIL_PASSWORD'] = xsaeccnuhttocaha
mail = Mail(app) # 实例化邮件对象
manager = Manager(app)
@app.route('/send_mail/')
def send_mail():
msg = Message(subject='邮件激活',recipients=['1234567@qq.com'],sender=app.config['MAIL_USERNAME'])
msg.html = render_template('emailhtml.html')
mail.send(msg)
return '发送邮件'
if __name__ == '__main__':
manager.run()
二、异步发送邮件
利用线程实现异步发送邮件,增加了用户的体验度,让用户先获取结果,而后在运行程序代码,利用from threading import Thread实现
实例
from flask import Flask,render_template
from flask_script import Manager
from flask_mail import Mail,Message
import os
from threading import Thread
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_USERNAME'] = '123456@qq.com'
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
mail = Mail(app)
manager = Manager(app)
# 异步发送
def send_mail_async(msg):
with app.app_context():
mail.send(msg)
@app.route('/send_mail/')
def send_mail():
msg = Message(subject='邮件激活',recipient=['123445@qq.com'],sender=app.config['MAIL_USERNAME'])
# 创建线程
thr = Thread(target=send_mail_async,args=[msg])
thr.start() # 开启线程
return '发送邮件'
if __name__ == '__main__':
manager.run()
详细
settings.py
class Config:
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:abcd1234@127.0.0.1:3306/tpp1806'
SQLALCHEMY_TRACK_MODIFICATIONS = False
# flask-mail 的配置信息
MAIL_USERNAME = 'chris_@126.com'
# 默认的发送者
MAIL_DEFAULT_SENDER = 'chris_@126.com'
MAIL_PASSWORD = 'abcd1234'
MAIL_SERVER = 'smtp.126.com'
ext.py
from flask_cache import Cache
from flask_mail import Mail
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
mail = Mail()
cache = Cache(config={'CACHE_TYPE': 'redis'})
def init_ext(app):
db.init_app(app=app)
Migrate(app=app, db=db)
mail.init_app(app=app)
cache.init_app(app=app)
import uuid
from flask import render_template, url_for
from flask_mail import Message
from flask_restful import Resource, reqparse, fields, marshal, marshal_with
from werkzeug.security import generate_password_hash
from App.ext import db, mail, cache
from App.models import User
parser = reqparse.RequestParser()
parser.add_argument('username', required=True, help='缺少用户名')
parser.add_argument('password', required=True, help='缺少密码')
parser.add_argument('email', required=True, help='缺少邮箱')
user_fields = {
'user_name': fields.String,
'e_mail': fields.String,
'是否激活': fields.Boolean(attribute='is_activity')
}
result_fields = {
'msg': fields.String,
'status': fields.Integer,
'data': fields.Nested(user_fields)
}
test_fields = {
'result': fields.String,
'hi': fields.String
}
class UerResource(Resource):
@marshal_with(test_fields)
def get(self):
# url = url_for('accountresource', _external=True, token='dfasdfk')
# print(url)
return {'result': 'hello', 'sss': 'mmmm'}
def post(self):
args = parser.parse_args()
username = args.get('username')
password = args.get('password')
email = args.get('email')
# 根据用户名生成一个HASH值
token = str(uuid.uuid5(uuid.NAMESPACE_DNS, username))
user = User()
user.user_name = username
user.password = generate_password_hash(password)
user.e_mail = email
user.token = token
# save里有异常的处理机制
msg = user.save()
# 如果有异常,直接返回
if msg.get('error'):
return msg
# 用户写入数据库成功
cache.set(token, user.id, timeout=60)
# 发送激活邮件
# 1. 创建一个Message对象
message = Message()
# 2. 配置Message
# 2.1 拿到post提交时填写的邮箱地址
message.recipients = [email]
# 2.2 设置邮箱的主题
message.subject = '欢迎注册1024网'
# 2.3 设置邮箱的内容
# http://127.0.0.1:5000/accounts/?token=
url = url_for('accountresource', _external=True, token=token)
message.html = render_template('ActivatePage.html', username=username,
activate_url=url)
# 2.4 设置发送者。如果在settings里设置里MAIL_DEFAULT_SENDER配置项,可以不再设置sender属性
# message.sender = 'chris@126.com'
# 3. 把Message对象发出去
mail.send(message)
# return {'msg': '注册成功', 'status': 201, 'data': user}
return marshal({'msg': '注册成功', 'status': 201, 'data': user}, result_fields)]]