""" 邮件验证服务 """ from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import secrets import smtplib import string from app.config import settings from app.log import logger class EmailService: """邮件发送服务""" def __init__(self): self.smtp_server = settings.smtp_server self.smtp_port = settings.smtp_port self.smtp_username = settings.smtp_username self.smtp_password = settings.smtp_password self.from_email = settings.from_email self.from_name = settings.from_name def generate_verification_code(self) -> str: """生成8位验证码""" # 只使用数字,避免混淆 return "".join(secrets.choice(string.digits) for _ in range(8)) async def send_verification_email(self, email: str, code: str, username: str) -> bool: """发送验证邮件""" try: msg = MIMEMultipart() msg["From"] = f"{self.from_name} <{self.from_email}>" msg["To"] = email msg["Subject"] = "邮箱验证 - Email Verification" # HTML 邮件内容 html_content = f"""

osu! 邮箱验证

Email Verification

你好 {username}!

感谢你注册我们的 osu! 服务器。为了完成账户验证,请输入以下验证码:

{code}

这个验证码将在 10 分钟后过期

注意:
  • 请不要与任何人分享这个验证码
  • 如果你没有请求此验证码,请忽略这封邮件
  • 验证码只能使用一次

如果你有任何问题,请联系我们的支持团队。


Hello {username}!

Thank you for registering on our osu! server. To complete your account verification, please enter the following verification code:

This verification code will expire in 10 minutes.

Important: Do not share this verification code with anyone. If you did not request this code, please ignore this email.

""" # noqa: E501 msg.attach(MIMEText(html_content, "html", "utf-8")) with smtplib.SMTP(self.smtp_server, self.smtp_port) as server: if self.smtp_username and self.smtp_password: server.starttls() server.login(self.smtp_username, self.smtp_password) server.send_message(msg) logger.info(f"Successfully sent verification code to {email}") return True except Exception as e: logger.error(f"Failed to send email: {e}") return False # 全局邮件服务实例 email_service = EmailService()