#!/usr/bin/env python # -*- coding: utf-8 -*- import smtplib import random import string from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import datetime def generate_verification_code(length=6): """生成随机验证码""" return ''.join(random.choices(string.digits, k=length)) def send_verification_email(smtp_host, smtp_port, to_email): """发送带验证码的邮件""" # 生成6位随机验证码 verification_code = generate_verification_code() # 创建邮件 msg = MIMEMultipart() msg['From'] = 'noreply@system.com' msg['To'] = to_email msg['Subject'] = f'您的验证码 - {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}' # 邮件正文 body = f'''

验证码

您好!

您的验证码是:

{verification_code}

此验证码将在30分钟内有效。

如果这不是您请求的,请忽略此邮件。

谢谢!

此邮件由系统自动发送,请勿回复。
''' msg.attach(MIMEText(body, 'html')) # 连接SMTP服务器并发送 try: server = smtplib.SMTP(smtp_host, smtp_port) server.set_debuglevel(1) # 开启调试模式 print(f"连接到SMTP服务器: {smtp_host}:{smtp_port}") # 发送邮件 server.sendmail(msg['From'], msg['To'], msg.as_string()) print(f"成功发送验证码邮件到: {to_email}") print(f"验证码: {verification_code}") server.quit() return True, verification_code except Exception as e: print(f"发送邮件失败: {str(e)}") return False, verification_code if __name__ == "__main__": # SMTP服务器设置 smtp_host = 'localhost' # 本地SMTP服务器 smtp_port = 25 # SMTP端口 # 收件人邮箱 to_email = 'testaa@nosqli.com' # 发送验证码邮件 success, code = send_verification_email(smtp_host, smtp_port, to_email) if success: print(f"验证码邮件已发送,验证码: {code}") else: print("邮件发送失败,请检查SMTP服务器设置")