-- Sending: SMTP submission via an outbox queue (server-architecture-spec.md ยง3.3). -- An IMAP username isn't necessarily an email address ("alice" vs -- "alice@example.com"), so the sender identity is stored explicitly. ALTER TABLE accounts ADD COLUMN email_address TEXT; ALTER TABLE accounts ADD COLUMN display_name TEXT; UPDATE accounts SET email_address = username WHERE username LIKE '%@%'; -- Sent mail lives alongside synced mail so a thread shows both sides of the -- conversation. Sync is one-way and only reads INBOX, so without this a -- reply would vanish from its own thread. Sent rows have no IMAP UID. ALTER TABLE messages ADD COLUMN source TEXT NOT NULL DEFAULT 'imap'; ALTER TABLE messages ALTER COLUMN uid DROP NOT NULL; ALTER TABLE messages ADD CONSTRAINT messages_uid_matches_source CHECK ((source = 'imap') = (uid IS NOT NULL)); CREATE TABLE outbox ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, -- draft: editable, never sent automatically -- pending: queued, waiting for next_attempt_at -- sending: claimed by the worker -- sent / failed: terminal (failed can be edited and re-queued) status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'pending', 'sending', 'sent', 'failed')), to_addrs TEXT[] NOT NULL DEFAULT '{}', cc_addrs TEXT[] NOT NULL DEFAULT '{}', bcc_addrs TEXT[] NOT NULL DEFAULT '{}', subject TEXT NOT NULL DEFAULT '', text_body TEXT NOT NULL DEFAULT '', -- Reply context, derived server-side from the parent message rather than -- trusted from the client. in_reply_to TEXT, references_ TEXT[] NOT NULL DEFAULT '{}', thread_id UUID, -- Assigned when first queued and reused on every retry, so if a server -- accepted a message but the ack was lost, the retry is recognisably the -- same message to recipients' clients rather than a new one. message_id TEXT, attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT, next_attempt_at TIMESTAMPTZ, sent_message_id UUID REFERENCES messages(id) ON DELETE SET NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), sent_at TIMESTAMPTZ ); CREATE INDEX outbox_due_idx ON outbox (next_attempt_at) WHERE status = 'pending'; CREATE INDEX outbox_user_status_idx ON outbox (user_id, status);