"""The scheduled send job (SPEC §6.5). Fires ``UNDO_SECONDS`` after the user hits send. If the outbox row was cancelled in the meantime, it does nothing (no SMTP traffic). Otherwise: SMTP send, append to Sent (skipped for Gmail, which self-appends), harvest recipients into ``known_recipients`` (weight 3), and publish ``message.sent``. """ from __future__ import annotations import logging import uuid from datetime import UTC, datetime from typing import Any from sqlalchemy import select from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.ext.asyncio import AsyncSession from app.db import session_scope from app.events import get_event_bus from app.indexer import blobstore from app.models import ( Account, ComposeAttachment, Draft, KnownRecipient, Mailbox, Message, Outbox, ) from app.outbox.mime_build import build_mime from app.sync.provider_factory import build_provider logger = logging.getLogger(__name__) def _is_gmail(account: Account) -> bool: host = str(account.imap_config.get("host", "")).lower() return "gmail.com" in host or "googlemail.com" in host async def _harvest_recipients(session: AsyncSession, user_id: uuid.UUID, emails: list[str]) -> None: now = datetime.now(UTC) for email in {e.lower() for e in emails if e}: stmt = pg_insert(KnownRecipient).values( user_id=user_id, email=email, name="", times_used=3, last_used_at=now ) stmt = stmt.on_conflict_do_update( index_elements=[KnownRecipient.user_id, KnownRecipient.email], set_={ "times_used": KnownRecipient.times_used + 3, # sent-to weight (SPEC §4) "last_used_at": stmt.excluded.last_used_at, }, ) await session.execute(stmt) async def _load_attachments( session: AsyncSession, user_id: uuid.UUID, draft: Draft ) -> list[tuple[str, str, bytes]]: """Resolve a draft's compose-attachment ids into (filename, mime, data) tuples.""" raw_ids = draft.payload.get("attachment_ids") or [] if not isinstance(raw_ids, list) or not raw_ids: return [] ids: list[uuid.UUID] = [] for value in raw_ids: try: ids.append(uuid.UUID(str(value))) except ValueError: continue if not ids: return [] rows = await session.scalars( select(ComposeAttachment).where( ComposeAttachment.id.in_(ids), ComposeAttachment.user_id == user_id ) ) by_id = {r.id: r for r in rows} out: list[tuple[str, str, bytes]] = [] for i in ids: att = by_id.get(i) if att is not None: out.append((att.filename, att.mime_type, blobstore.load(user_id, att.blob_sha256))) return out async def send_job(ctx: dict[str, Any], outbox_id: str) -> None: """Send a queued message unless it was cancelled during the undo window.""" oid = uuid.UUID(outbox_id) async with session_scope() as session: outbox = await session.get(Outbox, oid) if outbox is None or outbox.state != "undo_window": return # cancelled, or already handled -> no SMTP traffic outbox.state = "sending" draft = await session.get(Draft, outbox.draft_id) if draft is None: outbox.state = "failed" outbox.error = "draft missing" return account = await session.get(Account, draft.account_id) reply_to = ( await session.get(Message, draft.reply_to_message_id) if draft.reply_to_message_id else None ) if account is None: outbox.state = "failed" outbox.error = "account missing" return user_id = outbox.user_id attachments = await _load_attachments(session, user_id, draft) raw, envelope_from, envelope_to = build_mime(account, draft, reply_to, attachments) sent_path = await session.scalar( select(Mailbox.path).where( Mailbox.account_id == account.id, Mailbox.special_use == "sent" ) ) gmail = _is_gmail(account) account_obj = account provider = build_provider(account_obj) try: await provider.send(raw, envelope_from, envelope_to) if sent_path and not gmail: await provider.append(sent_path, raw, frozenset({"\\Seen"})) except Exception as exc: # noqa: BLE001 - record and notify, keep the draft async with session_scope() as session: ob = await session.get(Outbox, oid) if ob is not None: ob.state = "failed" ob.error = str(exc)[:500] await get_event_bus().publish( "outbox.state_changed", {"user_id": str(user_id), "outbox_id": str(oid), "state": "failed"}, ) logger.exception("send failed for outbox %s", oid) return finally: await provider.close() async with session_scope() as session: ob = await session.get(Outbox, oid) if ob is not None: ob.state = "sent" # The message left successfully: drop its draft so it no longer shows in # the Drafts folder (undo/cancel returns earlier, keeping the draft). draft_row = await session.get(Draft, draft.id) if draft_row is not None: await session.delete(draft_row) await _harvest_recipients(session, user_id, envelope_to) bus = get_event_bus() await bus.publish( "message.sent", {"user_id": str(user_id), "outbox_id": str(oid), "thread_id": str(draft.thread_id)}, ) await bus.publish( "outbox.state_changed", {"user_id": str(user_id), "outbox_id": str(oid), "state": "sent"}, )