安装模块
1 pip install flask 2 pip install flask-mail
开启邮箱授权码
进入qq邮箱->设置->账户->开启POP3/SMTP服务
代码块
config.py
1 MAIL_SERVER = 'smtp.qq.com' 2 MAIL_PORT = '587' 3 MAIL_USE_TLS = True 4 MAIL_USERNAME = '1045216729@qq.com' 5 MAIL_PASSWORD = 'mssmnlfqtykfbbee' 6 MAIL_DEFAULT_SENDER = '1045216729@qq.com' 7 MAIL_HEADER = '鸭梨视频信息验证通知' 8 MAIL_BODY = '验证码为:{}, 有效期为45分钟。'
app.py
1 from flask import Flask 2 from flask_mail import Mail,Message 3 app = Flask(__name__) 4 app.config.from_object('config') 5 mail = Mail(app) 6 7 class SingleEmail: 8 @classmethod 9 def send(cls,subject,to,code): 10 recipients = [] 11 recipients.append(to) 12 msg = Message(subject=subject,recipients=recipients) 13 msg.html = "<b style='color:red'>" + app.config['MAIL_BODY'].format(code) + "</b>" 14 mail.send(msg) 15 16 @app.route("/") 17 def index(): 18 single = SingleEmail() 19 single.send('Hello','imock@sina.com',520) 20 return '' 21 22 if __name__ == '__main__': 23 app.run()
参数说明
参数 | 类型 | 是否为空 | 说明 |
---|---|---|---|
MAIL_SERVER | string | 不能为空 | smtp服务器 |
MAIL_PORT | string | 不能为空 | smtp服务器端口 |
MAIL_USE_TLS | bool | 不能为空 | 是否使用TLS协议 |
MAIL_USERNAME | string | 不能为空 | 发件人邮箱 |
MAIL_PASSWORD | string | 不能为空 | 发件人授权码(非登录密码) |
MAIL_DEFAULT_SENDER | string | 可以为空 | 默认发件人邮箱 |
MAIL_HEADER | string | 可以为空 | 邮件主题 |
MAIL_BODY | string | 可以为空 | 邮件内容 |
recipients | list | 不能为空 | 收件人邮箱 |
html | string | 可以为空 | 以html方式渲染 |
data | string | 可以为空 | 以数据形式渲染,没有任何样式 |