安装所需库
pip install flask-mail
写mail配置参数
MAIL_SERVER = 'smtp.office365.com' # 邮箱服务商提供的smtp服务器
MAIL_USERNAME = 'flask_restful_test@outlook.com' # 邮箱地址
MAIL_PASSWORD = 'flask_restful_mail' # 邮箱密码,某些邮箱需使用客户端授权码
MAIL_PORT = 587 # smtp端口,默认为25
MAIL_USE_TLS = True # 是否用TLS加密,outlook需要,其他邮箱不一定
MAIL_DEFAULT_SENDER = ('FlaskRestful', MAIL_USERNAME) # 可迭代二元对象:(发送者姓名,发送者邮箱),也可只有一外发送邮箱
# MAIL_DEFAULT_SENDER = MAIL_USERNAME
app注册好邮箱参数后,用多线程发送邮件
from concurrent.futures.thread import ThreadPoolExecutor
executor = ThreadPoolExecutor(1) # 线程池
# 发送异步邮件函数需要放到app上下文中才能正确发送
def send_async_mail(app, msg):
with app.app_context():
mail.send(msg)
def send_mail(email: str = None, token: str = None):
print('发送邮件中...')
app = PUBLIC_VARIABLES['app']
if email and token:
msg = Message(subject='验证您的邮箱', recipients=[email, ])
msg.html = f'''
<span>点击下面的链接验证您的邮箱:</span>
<br>
<a href=#>点我验证</a>
<p>如果上面的链接无法点击,请复制下面的链接到浏览器中打开:</p>
<p>http://www.baidu.com</p>
<br><span>(链接有效期为5分钟,只能访问一次)</span>
'''
executor.submit(send_async_mail, app, msg)
else:
abort(400, error='验证邮件发送失败')
网友评论