This commit is contained in:
beabigegg
2025-08-28 08:59:46 +08:00
parent b9557250a4
commit 4f7f46b07a
42 changed files with 4992 additions and 494 deletions

100
utils.py
View File

@@ -165,33 +165,125 @@ from email.mime.text import MIMEText
from email.header import Header
from flask import current_app
def process_recipients(recipients_str):
"""
處理收件者字串,支援個人郵件和群組展開
輸入格式: "email1,email2,group:GroupName"
返回: 展開後的郵件地址列表
"""
print(f"[RECIPIENTS DEBUG] 開始處理收件者: {recipients_str}")
if not recipients_str:
print(f"[RECIPIENTS DEBUG] 收件者字串為空")
return []
recipients = [item.strip() for item in recipients_str.split(',') if item.strip()]
final_emails = []
for recipient in recipients:
print(f"[RECIPIENTS DEBUG] 處理收件者項目: {recipient}")
if recipient.startswith('group:'):
# 這是一個群組,需要展開
group_name = recipient[6:] # 移除 'group:' 前綴
print(f"[RECIPIENTS DEBUG] 發現群組: {group_name}")
try:
from ldap_utils import get_ldap_group_members
group_emails = get_ldap_group_members(group_name)
print(f"[RECIPIENTS DEBUG] 群組 {group_name} 包含 {len(group_emails)} 個成員")
for email in group_emails:
if email and email not in final_emails:
final_emails.append(email)
print(f"[RECIPIENTS DEBUG] 添加群組成員郵件: {email}")
except Exception as e:
print(f"[RECIPIENTS ERROR] 群組 {group_name} 展開失敗: {e}")
else:
# 這是個人郵件地址
if recipient and recipient not in final_emails:
final_emails.append(recipient)
print(f"[RECIPIENTS DEBUG] 添加個人郵件: {recipient}")
print(f"[RECIPIENTS DEBUG] 最終收件者列表 ({len(final_emails)} 個): {final_emails}")
return final_emails
def send_email(to_addrs, subject, body):
"""
Sends an email using the SMTP settings from the config.
Enhanced with detailed debugging information.
"""
print(f"[EMAIL DEBUG] 開始發送郵件...")
print(f"[EMAIL DEBUG] 收件者數量: {len(to_addrs)}")
print(f"[EMAIL DEBUG] 收件者: {to_addrs}")
print(f"[EMAIL DEBUG] 主旨: {subject}")
try:
# 取得 SMTP 設定
smtp_server = current_app.config['SMTP_SERVER']
smtp_port = current_app.config['SMTP_PORT']
use_tls = current_app.config['SMTP_USE_TLS']
sender_email = current_app.config['SMTP_SENDER_EMAIL']
sender_password = current_app.config['SMTP_SENDER_PASSWORD']
print(f"[EMAIL DEBUG] SMTP 設定:")
print(f"[EMAIL DEBUG] - 伺服器: {smtp_server}:{smtp_port}")
print(f"[EMAIL DEBUG] - 使用 TLS: {use_tls}")
print(f"[EMAIL DEBUG] - 寄件者: {sender_email}")
print(f"[EMAIL DEBUG] - 有密碼: {'' if sender_password else ''}")
# 建立郵件內容
print(f"[EMAIL DEBUG] 建立郵件內容...")
msg = MIMEText(body, 'html', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender_email
msg['To'] = ', '.join(to_addrs)
print(f"[EMAIL DEBUG] 郵件內容建立完成")
# 連接 SMTP 伺服器
print(f"[EMAIL DEBUG] 連接 SMTP 伺服器 {smtp_server}:{smtp_port}...")
server = smtplib.SMTP(smtp_server, smtp_port)
print(f"[EMAIL DEBUG] SMTP 伺服器連接成功")
if use_tls:
print(f"[EMAIL DEBUG] 啟用 TLS...")
server.starttls()
print(f"[EMAIL DEBUG] TLS 啟用成功")
if sender_password:
print(f"[EMAIL DEBUG] 登入 SMTP 伺服器...")
server.login(sender_email, sender_password)
print(f"[EMAIL DEBUG] SMTP 登入成功")
else:
print(f"[EMAIL DEBUG] 無需密碼認證")
# 發送郵件
print(f"[EMAIL DEBUG] 發送郵件...")
result = server.sendmail(sender_email, to_addrs, msg.as_string())
print(f"[EMAIL DEBUG] 郵件發送結果: {result}")
server.sendmail(sender_email, to_addrs, msg.as_string())
server.quit()
print(f"Email sent to {', '.join(to_addrs)}")
print(f"[EMAIL DEBUG] SMTP 連接已關閉")
print(f"[EMAIL SUCCESS] 郵件成功發送至: {', '.join(to_addrs)}")
return True
except Exception as e:
print(f"Failed to send email: {e}")
except smtplib.SMTPAuthenticationError as e:
print(f"[EMAIL ERROR] SMTP 認證失敗: {e}")
print(f"[EMAIL ERROR] 請檢查寄件者帳號和密碼設定")
return False
except smtplib.SMTPConnectError as e:
print(f"[EMAIL ERROR] SMTP 連接失敗: {e}")
print(f"[EMAIL ERROR] 請檢查 SMTP 伺服器設定")
return False
except smtplib.SMTPRecipientsRefused as e:
print(f"[EMAIL ERROR] 收件者被拒絕: {e}")
print(f"[EMAIL ERROR] 請檢查收件者郵件地址")
return False
except Exception as e:
print(f"[EMAIL ERROR] 郵件發送失敗: {type(e).__name__}: {e}")
import traceback
print(f"[EMAIL ERROR] 詳細錯誤:")
traceback.print_exc()
return False