| | |
| | import os |
| | import smtplib |
| | from email.message import EmailMessage |
| | from typing import Optional |
| |
|
| | def send_email_smtp(to: str, subject: str, body: str, attachment_path: Optional[str] = None): |
| | host = os.getenv("SMTP_HOST") |
| | port = int(os.getenv("SMTP_PORT", "587")) |
| | user = os.getenv("SMTP_USER") |
| | password = os.getenv("SMTP_PASS") |
| | sender = os.getenv("SMTP_FROM", user or "no-reply@example.com") |
| | use_tls = os.getenv("SMTP_USE_TLS", "1") == "1" |
| |
|
| | if not host or not user or not password: |
| | |
| | return True, "SMTP not configured; skipped sending (set SMTP_HOST/SMTP_PORT/SMTP_USER/SMTP_PASS/SMTP_FROM)" |
| |
|
| | msg = EmailMessage() |
| | msg["From"] = sender |
| | msg["To"] = to |
| | msg["Subject"] = subject |
| | msg.set_content(body) |
| |
|
| | if attachment_path: |
| | with open(attachment_path, "rb") as f: |
| | data = f.read() |
| | msg.add_attachment(data, maintype="application", subtype="pdf", filename=os.path.basename(attachment_path)) |
| |
|
| | try: |
| | with smtplib.SMTP(host, port) as server: |
| | if use_tls: |
| | server.starttls() |
| | server.login(user, password) |
| | server.send_message(msg) |
| | return True, "sent" |
| | except Exception as e: |
| | return False, f"send failed: {e}" |
| |
|