76 lines
2.4 KiB
Python
76 lines
2.4 KiB
Python
from flask import current_app
|
||
from flask_mail import Mail, Message
|
||
from threading import Thread
|
||
|
||
mail = Mail()
|
||
|
||
|
||
def send_async_email(app, msg):
|
||
"""异步发送邮件"""
|
||
with app.app_context():
|
||
try:
|
||
mail.send(msg)
|
||
except Exception as e:
|
||
print(f"邮件发送失败: {e}")
|
||
|
||
|
||
def send_email(to, subject, template, **kwargs):
|
||
"""发送邮件"""
|
||
app = current_app._get_current_object()
|
||
msg = Message(
|
||
subject=subject,
|
||
recipients=[to],
|
||
html=template,
|
||
sender=current_app.config['MAIL_DEFAULT_SENDER']
|
||
)
|
||
|
||
# 异步发送
|
||
thr = Thread(target=send_async_email, args=[app, msg])
|
||
thr.start()
|
||
return thr
|
||
|
||
|
||
def send_verification_email(email, code, code_type):
|
||
"""发送验证码邮件"""
|
||
type_map = {
|
||
1: '注册',
|
||
2: '登录',
|
||
3: '找回密码'
|
||
}
|
||
|
||
subject = f'【太白购物】{type_map.get(code_type, "验证")}验证码'
|
||
|
||
html_template = f"""
|
||
<!DOCTYPE html>
|
||
<html>
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<title>验证码邮件</title>
|
||
</head>
|
||
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
|
||
<div style="max-width: 600px; margin: 0 auto; padding: 20px;">
|
||
<div style="text-align: center; margin-bottom: 30px;">
|
||
<h2 style="color: #007bff;">太白购物平台</h2>
|
||
</div>
|
||
|
||
<div style="background: #f8f9fa; padding: 20px; border-radius: 5px; margin-bottom: 20px;">
|
||
<h3>您好!</h3>
|
||
<p>您正在进行<strong>{type_map.get(code_type, "验证")}</strong>操作,验证码为:</p>
|
||
<div style="text-align: center; margin: 20px 0;">
|
||
<span style="font-size: 24px; font-weight: bold; color: #007bff; background: #e9ecef; padding: 10px 20px; border-radius: 5px; letter-spacing: 2px;">{code}</span>
|
||
</div>
|
||
<p style="color: #666;">验证码有效期为10分钟,请及时使用。</p>
|
||
<p style="color: #666;">如果这不是您的操作,请忽略此邮件。</p>
|
||
</div>
|
||
|
||
<div style="text-align: center; color: #666; font-size: 12px;">
|
||
<p>此邮件由系统自动发送,请勿回复。</p>
|
||
<p>© 2025 太白购物平台 版权所有</p>
|
||
</div>
|
||
</div>
|
||
</body>
|
||
</html>
|
||
"""
|
||
|
||
return send_email(email, subject, html_template)
|