Files
ewoooc/scripts/archive/diagnose_email_issue.py
ogt 1b4f3a7bbe
Some checks failed
CD Pipeline / deploy (push) Failing after 59s
feat: EwoooC 初始化 — 完整專案推版至 Gitea
- 建立 Gitea Actions CD pipeline (.gitea/workflows/cd.yaml)
- 部署模式: rsync Python 檔案至 188 → docker restart (volume mount)
- Dockerfile/requirements 變動時自動重建 Docker image
- 部署通知: Telegram (開始/成功/失敗)
- 健康檢查: https://mo.wooo.work/health (最多 5 次重試)
- 同步最新 CLAUDE.md / ADR-008 / memory (2026-04-19)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 01:21:13 +08:00

187 lines
5.9 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 python3
# -*- coding: utf-8 -*-
"""
郵件問題診斷工具
檢查 SMTP 設定並提供修正建議
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import config
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def diagnose_smtp_config():
"""診斷 SMTP 設定"""
print("=" * 80)
print("📧 郵件設定診斷工具")
print("=" * 80)
print("\n1⃣ 當前 SMTP 設定:")
print("-" * 80)
print(f" SMTP 伺服器: {config.EMAIL_HOST}")
print(f" SMTP 埠號: {config.EMAIL_PORT}")
print(f" 寄件者: {config.EMAIL_SENDER}")
print(f" 登入帳號: {config.EMAIL_HOST_USER}")
print(f" 密碼: {'*' * len(config.EMAIL_HOST_PASSWORD)}")
# 判斷設定是否合理
print("\n2⃣ 設定分析:")
print("-" * 80)
is_pchome_email = '@pchome.tw' in config.EMAIL_HOST_USER
is_gmail_smtp = 'gmail.com' in config.EMAIL_HOST
if is_pchome_email and is_gmail_smtp:
print(" ❌ 錯誤:使用 PChome 郵件地址但設定 Gmail SMTP 伺服器")
print(" ⚠️ 這會導致認證失敗,郵件無法發送")
print("\n 💡 解決方案:")
print(" 請向 PChome IT 部門詢問以下資訊:")
print(" - SMTP 伺服器地址例如smtp.pchome.tw 或 mail.pchome.tw")
print(" - SMTP 埠號(通常是 587 或 465")
print(" - 是否需要使用 TLS/SSL")
print(" - 認證方式(帳號密碼或其他)")
return False
elif is_pchome_email:
print(" ⚠️ 使用 PChome 郵件,但 SMTP 伺服器不是 Gmail")
print(f" 當前 SMTP: {config.EMAIL_HOST}")
print(" 請確認此伺服器是否正確")
elif is_gmail_smtp:
print(" 使用 Gmail SMTP 伺服器")
if '@gmail.com' not in config.EMAIL_HOST_USER:
print(" ⚠️ 但寄件者不是 Gmail 地址,可能會有問題")
print("\n3⃣ 測試 SMTP 連線:")
print("-" * 80)
try:
print(" 正在連接 SMTP 伺服器...")
server = smtplib.SMTP(config.EMAIL_HOST, config.EMAIL_PORT, timeout=10)
print(" ✅ 成功連接到 SMTP 伺服器")
print(" 正在啟動 TLS 加密...")
server.starttls()
print(" ✅ TLS 加密啟動成功")
print(" 正在進行身份認證...")
server.login(config.EMAIL_HOST_USER, config.EMAIL_HOST_PASSWORD)
print(" ✅ 身份認證成功")
server.quit()
print("\n 🎉 SMTP 設定完全正確!")
return True
except smtplib.SMTPAuthenticationError as e:
print(f" ❌ 認證失敗: {e}")
print("\n 可能原因:")
print(" 1. 帳號或密碼錯誤")
print(" 2. 使用 PChome 郵件但 SMTP 伺服器設定為 Gmail")
print(" 3. 需要啟用「允許低安全性應用程式」Gmail")
print(" 4. 需要使用應用程式專用密碼Gmail")
return False
except smtplib.SMTPConnectError as e:
print(f" ❌ 連線失敗: {e}")
print("\n 可能原因:")
print(" 1. SMTP 伺服器地址錯誤")
print(" 2. 網路連線問題")
print(" 3. 防火牆封鎖")
return False
except Exception as e:
print(f" ❌ 未知錯誤: {e}")
return False
def test_send_email():
"""測試發送郵件"""
print("\n4⃣ 測試發送郵件:")
print("-" * 80)
try:
# 建立測試郵件
msg = MIMEMultipart('alternative')
msg['From'] = config.EMAIL_SENDER
msg['To'] = config.EMAIL_SENDER # 發給自己
msg['Subject'] = '【測試】MOMO 系統郵件測試'
# 純文字版本
text_body = """
這是一封測試郵件。
如果您收到這封郵件,表示 SMTP 設定正確。
此致
MOMO 監控系統
"""
# HTML 版本
html_body = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="font-family: 'Microsoft JhengHei', Arial, sans-serif; padding: 20px;">
<h2 style="color: #2c3e50;">✅ 測試郵件</h2>
<p>這是一封測試郵件。</p>
<p>如果您收到這封郵件,表示 SMTP 設定正確。</p>
<hr>
<p style="color: #7f8c8d; font-size: 12px;">此致<br>MOMO 監控系統</p>
</body>
</html>
"""
text_part = MIMEText(text_body, 'plain', 'utf-8')
html_part = MIMEText(html_body, 'html', 'utf-8')
msg.attach(text_part)
msg.attach(html_part)
# 發送
print(" 正在發送測試郵件...")
with smtplib.SMTP(config.EMAIL_HOST, config.EMAIL_PORT) as server:
server.starttls()
server.login(config.EMAIL_HOST_USER, config.EMAIL_HOST_PASSWORD)
server.sendmail(config.EMAIL_SENDER, [config.EMAIL_SENDER], msg.as_string())
print(" ✅ 測試郵件發送成功!")
print(f"\n 📬 請檢查信箱: {config.EMAIL_SENDER}")
print(" ⚠️ 如果沒收到,請檢查垃圾郵件資料夾")
return True
except Exception as e:
print(f" ❌ 發送失敗: {e}")
return False
def main():
"""主程式"""
# 診斷 SMTP 設定
smtp_ok = diagnose_smtp_config()
if smtp_ok:
# 如果 SMTP 設定正確,測試發送郵件
test_send_email()
else:
print("\n" + "=" * 80)
print("❌ SMTP 設定有問題,無法發送郵件")
print("=" * 80)
print("\n建議處理步驟:")
print("1. 確認您要使用的郵件系統PChome 或 Gmail")
print("2. 取得正確的 SMTP 伺服器設定")
print("3. 更新 .env 檔案中的設定")
print("4. 重新執行此診斷工具")
print("\n" + "=" * 80)
print("診斷完成")
print("=" * 80)
if __name__ == '__main__':
main()