使用163邮箱作为邮件发送邮箱,使用qq邮箱接收电子邮件
from flask import Flask
from flask_mail import Mail, Message
app = Flask(__name__)
# 给flask配置文件添加配置信息
# 这个配置信息类似一个字典,可以追加数据
app.config.update(
DEBUG = True,
MAIL_SERVER='smtp.163.com',
MAIL_PORT=465,
MAIL_USE_TLS = False, # SSL(Security Socket Layer,安全套接字层)和TLS(Transport Layer Sceurity,传输层安全)是两种常用的电子邮件安全协议
MAIL_USE_SSL = True,
MAIL_USERNAME = 'xxx@163.com',
MAIL_PASSWORD = 'xxx', # 授权码而不是邮箱登录密码。
)
# 创建邮件对象工具
mail = Mail(app)
# 异步发送电子邮件
from threading import Thread
def send_async_email(app,msg):
mail.send(msg)
def send_email(subject, sender, recipients, text_body, html_body):
msg = Message(subject, sender=sender, recipients=recipients) # # sender 发送方邮箱,recipients 接受方邮箱列表
msg.body = text_body # 纯文本信息
msg.html = html_body # HTML格式的信息
Thread(target=send_async_email,args=(app,msg)).start()
@app.route('/email')
def index():
send_email('test subject',app.config['MAIL_USERNAME'],['xxx@qq.com'], 'text body','<b>HTML</b> body')
return '发送成功'
if __name__ == '__main__':
app.run(port=5001, debug=True)