-
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
"""Outgoing email. Uses SMTP when configured; otherwise writes .eml files to OUTBOX_DIR
|
||||
so the full flow can be tested locally without sending real mail."""
|
||||
|
||||
import logging
|
||||
import smtplib
|
||||
import ssl
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from email.message import EmailMessage
|
||||
from pathlib import Path
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def send_email(
|
||||
to: str,
|
||||
subject: str,
|
||||
text: str,
|
||||
attachments: list[tuple[str, bytes, str]] | None = None,
|
||||
) -> str:
|
||||
"""Returns "smtp" or "outbox:<path>". Raises on SMTP failure."""
|
||||
msg = EmailMessage()
|
||||
msg["From"] = settings.MAIL_FROM
|
||||
msg["To"] = to
|
||||
msg["Subject"] = subject
|
||||
msg.set_content(text)
|
||||
for filename, data, mime in attachments or []:
|
||||
maintype, subtype = mime.split("/", 1)
|
||||
msg.add_attachment(data, maintype=maintype, subtype=subtype, filename=filename)
|
||||
|
||||
if settings.SMTP_HOST:
|
||||
with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT, timeout=20) as smtp:
|
||||
if settings.SMTP_STARTTLS:
|
||||
smtp.starttls(context=ssl.create_default_context())
|
||||
if settings.SMTP_USER:
|
||||
smtp.login(settings.SMTP_USER, settings.SMTP_PASSWORD)
|
||||
smtp.send_message(msg)
|
||||
return "smtp"
|
||||
|
||||
outbox = Path(settings.OUTBOX_DIR)
|
||||
outbox.mkdir(parents=True, exist_ok=True)
|
||||
path = outbox / f"{datetime.now():%Y%m%d-%H%M%S}-{uuid.uuid4().hex[:8]}.eml"
|
||||
path.write_bytes(bytes(msg))
|
||||
logger.info("SMTP not configured; email to %s saved to %s", to, path)
|
||||
return f"outbox:{path}"
|
||||
Reference in New Issue
Block a user