Spaces:
Sleeping
Sleeping
| import os | |
| import smtplib | |
| import hashlib | |
| from typing import List, Tuple | |
| from email.mime.text import MIMEText # ← 修正:email.mime.text | |
| def choose_subject(email: str, subject_a: str, subject_b: str) -> Tuple[str, str]: | |
| # 受信者ごとにハッシュで安定割当(50/50) | |
| h = hashlib.sha256(email.encode()).digest()[0] | |
| variant = "A" if (h % 2 == 0) else "B" | |
| return (subject_a if variant == "A" else subject_b), variant | |
| def send_email(recipients: List[str], subject_a: str, subject_b: str, body_md: str): | |
| host = os.getenv("SMTP_HOST", "") | |
| port = int(os.getenv("SMTP_PORT", "587")) | |
| user = os.getenv("SMTP_USERNAME", "") | |
| pwd = os.getenv("SMTP_PASSWORD", "") | |
| sender = os.getenv("EMAIL_FROM", user or "no-reply@example.com") | |
| # 資格情報が未設定ならスキップ(アプリは落とさない) | |
| if not host: | |
| return {"status": "skipped", "reason": "SMTP not configured"} | |
| results = [] | |
| with smtplib.SMTP(host, port) as s: | |
| s.starttls() | |
| if user and pwd: | |
| s.login(user, pwd) | |
| for rcpt in recipients: | |
| subject, variant = choose_subject(rcpt, subject_a, subject_b) | |
| msg = MIMEText(body_md, _subtype="plain", _charset="utf-8") | |
| msg["Subject"] = subject | |
| msg["From"] = sender | |
| msg["To"] = rcpt | |
| s.sendmail(user or sender, [rcpt], msg.as_string()) | |
| results.append({"to": rcpt, "variant": variant, "subject": subject}) | |
| return results | |