Design the web front end of an email client like Outlook on the web or Gmail.
The core experience:
Constraints:
Focus on the client: architecture, data model and sync, API, rendering of untrusted HTML, and performance, accessibility and offline.
An email client is a long-lived productivity app, closer to a desktop program than a website. Users keep it open for hours, act on hundreds of messages with the keyboard, and expect it to work on a train. And unlike most apps, the main content (HTML email) is hostile input written by strangers. The interesting parts are sync, list performance, safe rendering, and the composer.
from:, has:attachment, date ranges).| Concern | Target |
|---|---|
| Startup (warm) | inbox visible < 1 s from local cache; cold < 2.5 s |
| Open a message | < 100 ms when cached, < 500 ms otherwise |
| Actions | archive/delete reflected instantly (optimistic), INP < 100 ms for keyboard actions |
| List scale | smooth scrolling through 100k+ conversations in a folder |
| Memory | stable over an 8-hour session (no leaks from iframes, object URLs, listeners) |
| Offline | last ~30 days of mail readable; actions and drafts queued |
| Security | no script execution or tracking from email content; strict CSP |
Mail transport (SMTP/IMAP servers), spam filtering, calendar and contacts apps, admin settings.
Assume: threaded by default, labels as many-to-many (folders are a special case), 30-day offline cache opt-in, server search with local fallback.
A single-page app with a local data layer, similar in spirit to a chat client:
syncToken) plus push notifications of
changes (WebSocket/SSE).SSR adds little here (no SEO, personal data); a fast-loading shell from the service worker cache + local data gives a better warm start than server rendering.
<MailApp>
<TopBar> <SearchBox /> <AccountMenu /> <SyncStatus /> </TopBar>
<Shell>
<NavPane> <ComposeButton /> <FolderTree /> <LabelList /> </NavPane>
<ListPane>
<ListToolbar /> // select all, bulk actions, sort, filter
<MessageList> // virtualized
<ConversationRow />
<ReadingPane>
<ThreadHeader /> // subject, labels, actions
<ThreadMessages>
<MessageCard collapsed />
<MessageCard expanded>
<MessageHeader /> // from, to, date, security indicators
<SafeEmailBody /> // sandboxed iframe
<AttachmentList />
<InlineReply />
<ComposeWindows /> // multiple floating/docked composers
<UndoToast />
<ShortcutHelpDialog />
type ID = string;
interface Address { name?: string; email: string }
interface Message {
id: ID;
threadId: ID;
from: Address;
to: Address[];
cc: Address[];
bcc?: Address[]; // only on sent/draft
subject: string;
snippet: string; // plain text preview from server
receivedAt: string;
labelIds: ID[]; // INBOX, UNREAD, STARRED, user labels
hasAttachments: boolean;
bodyState: 'none' | 'loading' | 'loaded'; // bodies lazily fetched
body?: { html?: string; text?: string; sanitizedAt?: number };
attachments: { id: ID; filename: string; mimeType: string; size: number; inlineCid?: string }[];
headers: { messageId: string; inReplyTo?: string; references?: string[] };
security?: { spf: 'pass' | 'fail'; dkim: 'pass' | 'fail'; externalSender: boolean; encrypted?: boolean };
}
interface Thread {
id: ID;
messageIds: ID[]; // chronological
lastMessageAt: string;
participants: Address[];
labelIds: ID[]; // union of message labels
unreadCount: number;
subject: string;
snippet: string;
}
interface Label { id: ID; name: string; type: 'system' | 'user'; unreadCount: number; totalCount: number; color?: string }
interface Draft {
id: ID; // server draft id once saved
localId: ID; // client id; stable before first save
mode: 'new' | 'reply' | 'reply_all' | 'forward';
inReplyToMessageId?: ID;
to: Address[]; cc: Address[]; bcc: Address[];
subject: string;
bodyHtml: string; // editor output, sanitized on save
attachments: { localId: ID; uploadId?: ID; name: string; size: number; progress: number }[];
version: number; // increments per local edit; server stores latest
savedVersion: number;
}
interface MailStore {
threads: Record<ID, Thread>;
messages: Record<ID, Message>;
labels: Record<ID, Label>;
lists: Record<string, { // key: "label:INBOX|sort:date" or "search:from:ana"
threadIds: ID[];
nextPageToken?: string;
totalEstimate?: number;
}>;
selection: { listKey: string; ids: Set<ID>; anchorId?: ID; focusedId?: ID };
pendingActions: PendingAction[];
syncToken: string | null;
drafts: Record<ID, Draft>; // keyed by localId
}
type PendingAction =
| { id: ID; type: 'modifyLabels'; threadIds: ID[]; add: ID[]; remove: ID[]; createdAt: number }
| { id: ID; type: 'trash'; threadIds: ID[]; createdAt: number }
| { id: ID; type: 'send'; draftLocalId: ID; sendAt: number };
Design notes:
INBOX; read = remove UNREAD; star = add STARRED.
One mutation type (modifyLabels) covers most actions and makes optimistic updates and undo uniform (undo = the
inverse label change).INBOX disappears from the inbox list immediately).GET /api/threads?labelId=INBOX&pageSize=50&pageToken=CiAKGjBpNDd2Nmp2Zml2cXRwYjBpOXA0
{
"threads": [
{ "id": "th_1", "subject": "Q3 planning", "snippet": "Here's the draft agenda for…", "lastMessageAt": "2025-03-03T09:12:00Z",
"participants": [{ "name": "Priya", "email": "priya@example.com" }], "labelIds": ["INBOX", "UNREAD", "IMPORTANT"],
"unreadCount": 1, "messageIds": ["m_9", "m_14"] }
],
"messages": { "m_14": { "id": "m_14", "threadId": "th_1", "from": { "name": "Priya", "email": "priya@example.com" }, "receivedAt": "2025-03-03T09:12:00Z", "hasAttachments": true } },
"nextPageToken": "CiAKGjBpNDd2Nmp2Zml2cXRwYjBpOXA1",
"resultSizeEstimate": 18234
}
Cursor (page token) pagination: new mail arrives constantly at the top; offsets would shift. The estimate drives the
"1–50 of ~18,000" display and scrollbar sizing. Outlook-style "jump to date" needs a seekable index: a cursor
encoding a timestamp (before=2024-06-01) supports that.
GET /api/threads/th_1?format=full
-> { "thread": {...}, "messages": [ { "id": "m_14", "body": { "html": "<html>…</html>", "text": "…" }, "attachments": [...] } ] }
GET /api/messages/m_14/attachments/a_2 -> binary (Content-Disposition: attachment)
GET /api/sync?since=st_88210
-> { "changes": [
{ "type": "threadAdded", "thread": {...} },
{ "type": "labelsChanged", "threadId": "th_7", "labelIds": ["INBOX"] },
{ "type": "messageDeleted", "messageId": "m_3" }
], "syncToken": "st_88231", "hasMore": false }
-> 410 Gone { "error": "sync_token_expired" } // full resync of recent window
Push channel only says "something changed" ({ "type": "mailboxChanged", "historyId": "st_88231" }); the client
then calls /sync. This keeps push messages tiny and makes the delta API the single source of truth.
POST /api/threads/batchModify
{ "threadIds": ["th_1", "th_7"], "addLabelIds": [], "removeLabelIds": ["INBOX"], "clientActionId": "act_31" }
PUT /api/drafts/d_5 { "version": 12, "to": [...], "subject": "...", "bodyHtml": "...", "attachmentIds": ["up_3"] }
-> 200 { "id": "d_5", "version": 12 }
-> 409 { "error": "stale_version", "serverVersion": 13 } // edited in another tab/device
POST /api/drafts/d_5/send { "clientActionId": "send_d_5" }
Batch endpoints matter: "select all 2,000 and archive" must be one request (or a server-side job by query:
{ "query": "label:INBOX older_than:1y" }), not 2,000.
interface MessageListProps {
listKey: string;
threadIds: ID[];
selection: Set<ID>;
focusedId?: ID;
density: 'compact' | 'comfortable';
onOpen: (threadId: ID) => void;
onSelect: (threadId: ID, mode: 'single' | 'toggle' | 'range') => void;
onEndReached: () => void;
}
interface SafeEmailBodyProps {
html: string;
inlineAttachments: Record<string, string>; // cid -> blob/proxy URL
allowRemoteImages: boolean;
onLinkClick: (url: string) => void; // warning for mismatched link text, phishing checks
onHeightChange?: (px: number) => void;
}
interface ComposerProps {
draftLocalId: ID;
mode: Draft['mode'];
onClose: () => void;
onSend: () => void;
}
Email HTML can contain scripts, event handlers, forms that phish, CSS that overlays your UI, tracking pixels, and
<meta http-equiv="refresh">. Defence in depth:
<script>, on* attributes,
javascript: URLs, <form>, <object>, <embed>, <base>, <meta>; allow a vetted set of tags, attributes
and CSS properties. Rewrite cid: references to attachment URLs.<iframe sandbox> with no allow-scripts and no allow-same-origin, rendered from srcdoc
(or a separate cookieless origin). Even if sanitization misses something, script can't run and the frame can't
touch the app's cookies or DOM. Add allow-popups + allow-popups-to-escape-sandbox only so links can open in
a new tab.<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data: cid:; style-src 'unsafe-inline'">)
and a strict CSP for the app (nonces, object-src 'none', Trusted Types to prevent accidental
innerHTML in app code).href, open with
rel="noopener noreferrer".ResizeObserver (needs a tiny trusted script — or measure from the parent: the parent can read
contentDocument height only if same-origin, which conflicts with no allow-same-origin; a common compromise
is server-provided height estimates plus a dedicated sandbox origin that posts its height via postMessage).Trade-off to state: a separate sandbox origin with a minimal trusted resize script gives the best UX (exact
heights, dark-mode adjustments) with strong isolation; pure srcdoc without scripts is simplest and safest but
needs fixed/estimated heights or scrolling frames.
Intl.DateTimeFormat instance (constructing formatters is surprisingly expensive in
a loop).sendAt) for N seconds.online, and on focus after being hidden.BroadcastChannel), like a chat client; all tabs share IndexedDB.navigator.storage.persist()); actions and drafts queue in the persistent action queue; "Send" while offline
goes to the Outbox and is sent on reconnect.contenteditable via a framework (ProseMirror/Tiptap, Lexical) rather than raw
execCommand (deprecated and inconsistent). The output HTML is sanitized before saving/sending.visibilitychange; versioned
saves so two tabs editing the same draft detect conflicts (409 → "This draft was edited elsewhere").In-Reply-To, References)
server-side.j/k next/previous, o/Enter open, e archive, # delete, r/a/f reply/all/forward, c
compose, / search, x select, ? help. Disabled while typing in inputs; user can turn single-key shortcuts off
(WCAG 2.1.4 Character Key Shortcuts).grid or listbox with roving tabindex/aria-activedescendant; selection announced
("Selected, 3 of 50"). Row accessible names include unread state, sender, subject, date, attachment.F6 to cycle panes (Outlook convention).title ("Message body"); email content may be inaccessible itself, so offer a plain-text
view.lists["search:…"]).dir="auto" per message and
subject; the app chrome flips for RTL locales.srcdoc, proxying images for privacy), and sets up CSP reporting to detect failures in production.Why not render email HTML directly into a div after sanitizing? Sanitizers have bugs and email CSS would leak into the app (and app CSS into the email). An iframe sandbox adds isolation that doesn't depend on the sanitizer being perfect.
How do you show "1–50 of 18,234" when lists are cursor-paginated? Use the server's estimate; exact counts on huge mailboxes are expensive and change constantly.
How does "select all 18,000 and delete" work? The client sends a query-based batch operation; the server runs it as a job and streams progress; the client optimistically empties the visible list and reconciles via sync.
How do you make the inbox appear in under a second? Service worker cached shell + IndexedDB-cached first page of the inbox rendered immediately, then delta sync in the background.
How do you handle tracking pixels? Block remote images by default for unknown senders, proxy all images, and optionally prefetch them server-side so open-time can't be inferred.
Spotted a mistake or a rights concern? Report an issue