File size: 4,747 Bytes
133609a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import os
import ssl
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Email Configuration
SMTP_SERVER = os.environ.get("SMTP_SERVER")
SMTP_PORT = int(os.environ.get("SMTP_PORT", 465)) # Default to 465 for SSL
SMTP_USERNAME = os.environ.get("SMTP_USERNAME")
SMTP_PASSWORD = os.environ.get("SMTP_PASSWORD")
SENDER_EMAIL = os.environ.get("SENDER_EMAIL")
SENDER_NAME = os.environ.get("SENDER_NAME", "Test Sender")

def test_send_email(to_email: str, subject: str, body: str):
    print("--- 开始邮件发送测试流程 ---")
    print(f"加载环境变量: SMTP_SERVER={SMTP_SERVER}, SMTP_PORT={SMTP_PORT}, SENDER_EMAIL={SENDER_EMAIL}")

    if not all([SMTP_SERVER, SMTP_USERNAME, SMTP_PASSWORD, SENDER_EMAIL]):
        print("错误: SMTP配置不完整。请检查 .env 文件中的 SMTP_SERVER, SMTP_USERNAME, SMTP_PASSWORD, SENDER_EMAIL。")
        return False

    msg = MIMEText(body, 'plain', 'utf-8')
    msg['From'] = f"{SENDER_NAME} <{SENDER_EMAIL}>"
    msg['To'] = Header(to_email, 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    print("邮件内容构建完成。")
    print(f"发件人: {msg['From']}, 收件人: {msg['To']}, 主题: {msg['Subject']}")

    email_sent_successfully = False # 新增标志变量

    try:
        if SMTP_PORT == 587:
            print(f"尝试通过端口 {SMTP_PORT} 连接到 SMTP 服务器: {SMTP_SERVER} (使用 STARTTLS)")
            with smtplib.SMTP(SMTP_SERVER, SMTP_PORT, timeout=10) as server:
                server.set_debuglevel(1) # 设置调试级别为1,打印SMTP交互日志
                print("SMTP 服务器连接成功。")
                print("尝试启动 TLS...")
                server.starttls(context=ssl.create_default_context())
                print("TLS 启动成功。")
                print(f"尝试使用用户 {SMTP_USERNAME} 登录...")
                server.login(SMTP_USERNAME, SMTP_PASSWORD)
                print("SMTP 登录成功。")
                print(f"尝试发送邮件从 {SENDER_EMAIL}{to_email}...")
                server.sendmail(SENDER_EMAIL, to_email, msg.as_string())
                print(f"邮件发送成功至 {to_email}!")
                email_sent_successfully = True # 设置标志为True
        
        elif SMTP_PORT == 465:
            print(f"尝试通过端口 {SMTP_PORT} 连接到 SMTP 服务器: {SMTP_SERVER} (使用 SSL/TLS)")
            context = ssl.create_default_context()
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
            with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, context=context, timeout=10) as server:
                server.set_debuglevel(1) # 设置调试级别为1,打印SMTP交互日志
                print("SMTP_SSL 服务器连接成功。")
                print(f"尝试使用用户 {SMTP_USERNAME} 登录...")
                server.login(SMTP_USERNAME, SMTP_PASSWORD)
                print("SMTP 登录成功。")
                print(f"尝试发送邮件从 {SENDER_EMAIL}{to_email}...")
                server.sendmail(SENDER_EMAIL, to_email, msg.as_string())
                print(f"邮件发送成功至 {to_email}!")
                email_sent_successfully = True # 设置标志为True
        else:
            print(f"错误:不支持的端口 {SMTP_PORT}。目前只支持 465 (SSL) 和 587 (STARTTLS)。")
            # email_sent_successfully 保持为 False

    except smtplib.SMTPAuthenticationError:
        print("认证失败:请检查 .env 文件中的 SMTP_USERNAME 和 SMTP_PASSWORD。对于 QQ 邮箱,请确保使用的是授权码而非登录密码。")
    except smtplib.SMTPConnectError as e:
        print(f"连接失败:请检查 SMTP_SERVER 地址、SMTP_PORT 端口是否正确,以及网络防火墙设置。错误详情: {e}")
    except smtplib.SMTPServerDisconnected as e:
        print(f"SMTP 服务器意外断开连接。错误详情: {e}")
    except smtplib.SMTPException as e:
        print(f"SMTP 协议错误:{e}")
    except Exception as e:
        print(f"发生未知错误: {e}")
    finally:
        print("--- 邮件发送测试流程结束 ---")
    
    return email_sent_successfully # 根据标志变量返回最终结果

if __name__ == "__main__":
    test_to_email = "geqintan@qq.com"
    test_subject = "SuperProxy 测试邮件"
    test_body = "这是一封来自 SuperProxy 的测试邮件。"
    success = test_send_email(test_to_email, test_subject, test_body)
    if success:
        print("测试邮件发送过程完成。请检查收件箱。")
    else:
        print("测试邮件发送过程失败。")