Files
emailsystem/send_verification_email.py
2025-02-25 19:50:00 +08:00

80 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/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'''
<html>
<body>
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #eee; border-radius: 5px;">
<h2 style="color: #333;">验证码</h2>
<p>您好!</p>
<p>您的验证码是:</p>
<div style="background-color: #f7f7f7; padding: 15px; font-size: 24px; font-weight: bold; text-align: center; letter-spacing: 5px; margin: 20px 0; border-radius: 4px;">
{verification_code}
</div>
<p>此验证码将在30分钟内有效。</p>
<p>如果这不是您请求的,请忽略此邮件。</p>
<p>谢谢!</p>
<div style="margin-top: 30px; padding-top: 15px; border-top: 1px solid #eee; font-size: 12px; color: #999;">
此邮件由系统自动发送,请勿回复。
</div>
</div>
</body>
</html>
'''
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 = 3825 # 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服务器设置")