#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 測試 PChome SMTP 伺服器連線 """ import smtplib import socket import pytest def _probe_smtp_server(host, port, timeout=5): """測試 SMTP 伺服器是否可連接""" ok = True try: print(f"\n🔍 測試: {host}:{port}") print(f" 正在連接...") server = smtplib.SMTP(host, port, timeout=timeout) response = server.ehlo() print(f" ✅ 連接成功!") print(f" 伺服器回應: {response[1].decode('utf-8', errors='ignore')[:100]}...") # 檢查是否支援 STARTTLS if server.has_extn('STARTTLS'): print(f" ✅ 支援 STARTTLS 加密") server.quit() ok = True except socket.gaierror as e: print(f" ❌ DNS 解析失敗(伺服器不存在)") ok = False except socket.timeout: print(f" ❌ 連接逾時") ok = False except ConnectionRefusedError: print(f" ❌ 連接被拒絕(埠號可能不對)") ok = False except Exception as e: print(f" ❌ 錯誤: {e}") ok = False return ok def test_smtp_server(host, port, timeout=5): """測試 SMTP 伺服器是否可連接""" if not _probe_smtp_server(host, port, timeout): pytest.skip(f"SMTP 無法連線:{host}:{port}") def main(): """測試常見的 PChome SMTP 伺服器""" print("=" * 80) print("🔍 PChome SMTP 伺服器掃描") print("=" * 80) print("\n正在測試常見的 PChome SMTP 伺服器地址...") # 常見的伺服器地址和埠號組合 servers_to_test = [ ('smtp.pchome.tw', 587), ('smtp.pchome.tw', 465), ('smtp.pchome.tw', 25), ('mail.pchome.tw', 587), ('mail.pchome.tw', 465), ('mail.pchome.tw', 25), ('smtp.pchome.com.tw', 587), ('smtp.pchome.com.tw', 465), ('mail.pchome.com.tw', 587), ('mail.pchome.com.tw', 465), ] successful_servers = [] for host, port in servers_to_test: if _probe_smtp_server(host, port): successful_servers.append((host, port)) # 顯示結果 print("\n" + "=" * 80) print("📊 測試結果") print("=" * 80) if successful_servers: print(f"\n✅ 找到 {len(successful_servers)} 個可用的 SMTP 伺服器:") for host, port in successful_servers: print(f" • {host}:{port}") print("\n💡 建議:") print(f" 請將 .env 中的 EMAIL_HOST 改為: {successful_servers[0][0]}") print(f" 請將 .env 中的 EMAIL_PORT 改為: {successful_servers[0][1]}") else: print("\n❌ 未找到可用的 SMTP 伺服器") print("\n可能的原因:") print(" 1. PChome 的 SMTP 伺服器名稱與常見命名規則不同") print(" 2. SMTP 伺服器可能只允許內部網路連接") print(" 3. 需要 VPN 才能連接") print("\n建議:") print(" 請聯絡 PChome IT 部門,詢問正確的 SMTP 伺服器設定") print(" 或檢查公司內部文件、Outlook/郵件客戶端設定") print("\n" + "=" * 80) if __name__ == '__main__': main()