-
安装
pip install Flask-Mail
-
导入模块
from flask_mail import Mail, Message
-
配置参数
MAIL_SERVER : default ‘localhost’ MAIL_PORT : default 25 MAIL_USE_TLS : default False MAIL_USE_SSL : default False MAIL_DEBUG : default app.debug MAIL_USERNAME : default None MAIL_PASSWORD : default None MAIL_DEFAULT_SENDER : default None MAIL_MAX_EMAILS : default None MAIL_SUPPRESS_SEND : default app.testing MAIL_ASCII_ATTACHMENTS : default False
-
跟app绑定
mail = Mail() app = Flask(__name__) mail.init_app(app)
-
发送邮件
manage = Message( # 邮件头 "subject", # 给那个邮箱发 recipients=[email], # 发送的内容 body="content" ) # 发送邮件 mail.send(manage)
案列
- config.py
- exts.py
from flask_sqlalchemy import SQLAlchemy from flask_mail import Mail # 创建sqlalchemy对象 db = SQLAlchemy() # 创建mail对象 mail = Mail()
- main_cms.py
from flask import Flask from flask_wtf import CSRFProtect from apps.cms.views import bp as cms_bp from apps.common.views import bp as common_bp from apps.front.views import bp as front_bp from exts import db, mail import config def create_app(): app = Flask(__name__) # 把配置文件绑定到app中 app.config.from_object(config) app.register_blueprint(cms_bp) app.register_blueprint(common_bp) app.register_blueprint(front_bp) # 把db绑定到app中 db.init_app(app) # 绑定发送邮箱 mail.init_app(app) # 跟app添加csrf防护 CSRFProtect(app) return app if __name__ == "__main__": app = create_app() app.run(port=8000)
- views.py
from flask import request from exts import mail # restful 自己定义的返回信息 # xgcache 是自己封装的memcache缓存 from utils import restful, xgcache import string import re import random @bp.route("/email_captcha/") @login_required def email_captcha(): email = request.args.get("email") if email: result = re.match("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$", email) if result: # if xgcache.get(g.cms_user.id): # return restful.success("请60秒后重试, 感谢您的配合...") # string.ascii_letters 是小写a-z和大写A-Z拼成的字符串 source = list(string.ascii_letters) # extend 把括号里的了列表添加到source中 # map 第一个参数函数 # 第二个参数可迭代对象 source.extend(map(lambda x: str(x), range(10))) # sample 第一个参数是列表 第二个参数是指定你要的个数 从source里面随机的采取6位 captcha = random.sample(source, 6) # 把列表拼接成字符串 captcha = "".join(captcha) manage = Message( # 邮件头 "Python论坛邮箱验证码", # 发送的邮箱 recipients=[email], # 发送的内容 body="您的验证码是:%s" % captcha ) try: mail.send(manage) xgcache.set(email, captcha) return restful.success(message="ok") except Exception as e: return restful.server_error(message="服务器错误") else: return restful.params_error(message="邮箱格式不正确")