Skip to content

Show Inbound Conversations in Your Application ​

Inbound Conversations brings replies to your emails back into Outbound. This guide shows how to put them in front of your team inside your own application, as an inbox that works the way Gmail and Outlook do: a list of conversations on the left and the open conversation on the right, with your team's answers sent from the same place.

The examples use Express on the server and React in the browser. The same steps work with any stack. For the methods and every field, see the Conversations reference. For webhooks and syncing replies into your own database, see the Conversations guide.

text
┌─────────────────────────────┬───────────────────────────────────────────────┐
│ [Needs reply] Open  Closed  │ Your application is complete                  │
│ Search name, email, subject │ Riya Sharma <riya@example.com>      [Close]   │
├─────────────────────────────┼───────────────────────────────────────────────┤
│ ● Riya Sharma      10:42 AM │ ▸ Your email: Your application is complete    │
│   Your application is co... │                                               │
│   What are the fees for...  │ ┌ Riya Sharma                       10:42 AM ┐ │
│   [Needs reply]             │ │ What are the fees for the programme?       │ │
├─────────────────────────────┤ │ Riya Sharma, Applicant          [•••]      │ │
│   Arjun Mehta     Yesterday │ └────────────────────────────────────────────┘ │
│   Interview slot            │                                               │
│   Can I move it to Friday?  │        ┌ Admissions Team            10:51 AM ┐ │
│                             │        │ The fee is listed on our website.   │ │
│        [Load more]          │        └─────────────────────────────────────┘ │
│                             ├───────────────────────────────────────────────┤
│                             │ Replying to riya@example.com from Admissions  │
│                             │ [ Write a reply...                    ] [Send] │
└─────────────────────────────┴───────────────────────────────────────────────┘

Before You Start ​

  1. An Outbound admin has turned on Inbound Conversations for your account. You can ask for it from Settings in the dashboard, or from My Quota.
  2. You send the emails you want replies to with captureReplies: true. Only those emails create conversations. Add createThread: true as well to open each conversation when its email is sent, so the inbox also lists emails nobody has replied to yet.

How the Pieces Fit ​

text
Your app in the browser  ──►  Your server  ──►  Outbound SDK  ──►  Outbound
       (React)                (your login)      (your API key)

Your API key can read every conversation on your account and send email as you, so it stays on your server. The browser talks to a few routes on your server, your server checks that the person is allowed to see the inbox, and only then calls the SDK.

Step 1: Add Inbox Routes to Your Server ​

Five routes cover the whole inbox. This example uses Express 5, which passes errors from async handlers to your error handler. On Express 4, wrap each handler so a rejected promise reaches next.

ts
import express from 'express';
import { Readable } from 'node:stream';
import { Outbound } from '@masters-union/outbound-sdk';

const outbound = new Outbound({ apiKey: process.env.OUTBOUND_API_KEY });
const app = express();
app.use(express.json());

// Your own login check. Only people who may read replies get past it.
app.use('/api/inbox', requireStaff);

const FILTERS = {
  needsReply: { status: 'all', needsReply: true },
  open: { status: 'open' },
  closed: { status: 'closed' },
  all: { status: 'all' },
};

// The conversation list, 25 at a time.
app.get('/api/inbox/threads', async (req, res) => {
  const { threads, pagination } = await outbound.conversations.listThreads({
    ...(FILTERS[req.query.filter] ?? FILTERS.needsReply),
    q: req.query.q || undefined,
    cursor: req.query.cursor || undefined,
    limit: 25,
  });
  res.json({ threads, nextCursor: pagination.hasMore ? pagination.nextCursor : null });
});

// One conversation with all its messages. Opening it marks it read.
app.get('/api/inbox/threads/:threadId', async (req, res) => {
  const result = await outbound.conversations.getThread(req.params.threadId);
  if (result.thread.unreadCount > 0) {
    await outbound.conversations.updateThread(req.params.threadId, { read: true });
  }
  res.json(result);
});

// The formatted body of one message.
app.get('/api/inbox/messages/:messageId/html', async (req, res) => {
  const { html, displayHtml } = await outbound.conversations.getMessageHtml(req.params.messageId, { images: true });
  res.json({ html, displayHtml });
});

// Send a reply. draftId makes a retried request safe: the reply is sent once.
app.post('/api/inbox/threads/:threadId/replies', async (req, res) => {
  const result = await outbound.conversations.reply(req.params.threadId, {
    text: req.body.text,
    idempotencyKey: req.body.draftId,
  });
  res.status(202).json(result);
});

// Close or reopen a conversation.
app.patch('/api/inbox/threads/:threadId', async (req, res) => {
  const { thread } = await outbound.conversations.updateThread(req.params.threadId, { status: req.body.status });
  res.json({ thread });
});

// Attachments, streamed through your server so the API key stays here.
app.get('/api/inbox/messages/:messageId/attachments/:attachmentId', async (req, res) => {
  const { messageId, attachmentId } = req.params;
  const upstream = await fetch(
    `https://outbound-api.unionstack.in/v1/conversations/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}`,
    { headers: { 'X-Api-Key': process.env.OUTBOUND_API_KEY } },
  );
  if (!upstream.ok) return res.sendStatus(upstream.status);
  res.set('Content-Type', upstream.headers.get('content-type') ?? 'application/octet-stream');
  res.set('Content-Disposition', upstream.headers.get('content-disposition') ?? 'attachment');
  Readable.fromWeb(upstream.body).pipe(res);
});

Several Outbound accounts

If your application serves several customers, each with their own Outbound account, pass that customer's key as the last argument: outbound.conversations.listThreads(params, { apiKey }). See Configuration.

Step 2: Lay Out the Inbox ​

Two panes side by side, like an email client. On a phone, show one at a time: the list, then the conversation with a back button.

Each row in the list shows:

WhatField
Wholead.name, or lead.email when there is no name
WhenlastMessageAt, as a time for today and a date before that
Subjectsubject
Latest messagelastSnippet, cut to two lines
Unread dot and bold textunreadCount > 0
Needs reply badgeneedsReply
Asked to stop badgeoptOutDetected

Filters above the list: Needs reply, Open, Closed, and a search box. Needs reply is the best default view: it holds the conversations where the last message came from the other person.

Each conversation shows, oldest message first:

MessagekindHow to show it
Your email that started itoriginalA collapsed row at the top, "Your email: subject", that expands to the email
The person's replyreplyA bubble on the left with their name and time
Your team's replystaff_replyA bubble on the right. direction: 'outbound' was sent from Outbound; 'inbound' was sent from your own mailbox
Out of office, delivery failure, read receiptauto_reply, bounce, read_receiptA small collapsed row. Use "Out of office" when outOfOffice is true

Also worth showing on a message:

  • recipient.role === 'cc': the reply came from someone you copied. Label it "CC".
  • participant === 'external': the reply came from someone you never emailed, usually because the email was forwarded. Label it "Forwarded".
  • senderAuth === 'failed': the sender could not be verified. Warn your team to be careful with links and attachments.
  • optOut.detected: the person asked to stop receiving emails. Show it prominently.
  • attachments with inline: false: list them by name and size, with a download link to your attachment route.

Step 3: Show Each Email the Way Gmail Does ​

Replies are HTML emails. Two things make them read like they do in Gmail:

  1. Show the new part first. getMessageHtml returns displayHtml, the message with the quoted earlier emails removed, and html, the whole message. Show displayHtml, with a small "•••" button under it that switches to html. displayHtml is null when there was nothing to remove, so show html then.
  2. Render it in a sandboxed iframe, never with innerHTML. An email's own styles would otherwise restyle your application, and your styles would restyle the email. The sandbox below has no allow-scripts, so nothing in an email can run. allow-same-origin only lets your page read the frame's height.

When a message has no HTML (hasHtml is false), show newText: the plain text without the quoted history.

tsx
const FRAME_CSS = [
  'body{margin:0;padding:12px 14px;background:#fff;color:#222;font:13px/1.45 Arial,Helvetica,sans-serif;overflow-wrap:anywhere}',
  'img{max-width:100%;height:auto}',
].join('');

function EmailFrame({ html }: { html: string }) {
  const ref = useRef<HTMLIFrameElement>(null);
  const [height, setHeight] = useState(60);
  const srcDoc = `<!doctype html><html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><base target="_blank"><style>${FRAME_CSS}</style></head><body>${html}</body></html>`;

  useEffect(() => {
    const frame = ref.current;
    if (!frame) return;
    let observer: ResizeObserver | undefined;
    const measure = () => {
      const body = frame.contentDocument?.body;
      if (!body) return;
      setHeight(body.scrollHeight);
      observer?.disconnect();
      observer = new ResizeObserver(() => setHeight(body.scrollHeight));
      observer.observe(body);
    };
    frame.addEventListener('load', measure);
    return () => {
      frame.removeEventListener('load', measure);
      observer?.disconnect();
    };
  }, [srcDoc]);

  return (
    <iframe
      ref={ref}
      title="Email"
      srcDoc={srcDoc}
      sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox"
      style={{ width: '100%', height, border: 0, borderRadius: 8, background: '#fff' }}
    />
  );
}

function EmailBody({ messageId }: { messageId: string }) {
  const [body, setBody] = useState<{ html: string; displayHtml: string | null } | null>(null);
  const [showAll, setShowAll] = useState(false);

  useEffect(() => {
    api(`/messages/${messageId}/html`).then(setBody);
  }, [messageId]);

  if (!body) return <div className="body-placeholder" />;
  const trimmed = Boolean(body.displayHtml);
  return (
    <>
      <EmailFrame html={trimmed && !showAll ? body.displayHtml! : body.html} />
      {trimmed && (
        <button className="quote-toggle" onClick={() => setShowAll((v) => !v)} title={showAll ? 'Hide trimmed content' : 'Show trimmed content'}>
          {showAll ? 'Hide trimmed content' : '•••'}
        </button>
      )}
    </>
  );
}

Images

{ images: true } loads the images in an email, the way Gmail does, so signatures and logos appear. Loading an image tells the server that hosts it that someone opened the email. For more privacy, leave images off: the response then counts the removed images in remoteImagesBlocked, and you can offer a "Show images" button that fetches again with images: true. Tracking pixels are always removed.

Step 4: Build the Inbox ​

The rest of the browser code: the list, the conversation, each message and the reply box. It calls the routes from Step 1. Put it in the same file as EmailFrame and EmailBody from Step 3.

tsx
import { useEffect, useRef, useState } from 'react';
import type { ConversationMessage, ConversationThread } from '@masters-union/outbound-sdk';

async function api(path: string, init?: RequestInit) {
  const res = await fetch(`/api/inbox${path}`, { headers: { 'Content-Type': 'application/json' }, ...init });
  const body = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(body.error || body.message || 'Something went wrong. Try again.');
  return body;
}

const when = (iso: string) => {
  const date = new Date(iso);
  return date.toDateString() === new Date().toDateString()
    ? date.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })
    : date.toLocaleDateString([], { day: 'numeric', month: 'short' });
};

export function Inbox() {
  const [filter, setFilter] = useState('needsReply');
  const [selectedId, setSelectedId] = useState<string | null>(null);

  return (
    <div className="inbox">
      <ThreadList filter={filter} onFilter={setFilter} selectedId={selectedId} onSelect={setSelectedId} />
      {selectedId
        ? <ThreadView key={selectedId} threadId={selectedId} />
        : <p className="inbox-empty">Pick a conversation to read the replies and answer them.</p>}
    </div>
  );
}

function ThreadList({ filter, onFilter, selectedId, onSelect }: {
  filter: string;
  onFilter: (f: string) => void;
  selectedId: string | null;
  onSelect: (id: string) => void;
}) {
  const [threads, setThreads] = useState<ConversationThread[]>([]);
  const [nextCursor, setNextCursor] = useState<string | null>(null);
  const [q, setQ] = useState('');

  const load = async (cursor?: string) => {
    const params = new URLSearchParams({ filter, ...(q && { q }), ...(cursor && { cursor }) });
    const page = await api(`/threads?${params}`);
    setThreads((current) => (cursor ? [...current, ...page.threads] : page.threads));
    setNextCursor(page.nextCursor);
  };

  useEffect(() => {
    load();
    const timer = setInterval(() => load(), 30_000);
    return () => clearInterval(timer);
  }, [filter, q]);

  return (
    <aside className="thread-list">
      <nav className="filters">
        {[['needsReply', 'Needs reply'], ['open', 'Open'], ['closed', 'Closed']].map(([value, label]) => (
          <button key={value} aria-pressed={filter === value} onClick={() => onFilter(value)}>{label}</button>
        ))}
      </nav>
      <input type="search" placeholder="Search name, email or subject" value={q} onChange={(e) => setQ(e.target.value)} />

      {threads.length === 0 && <p className="list-empty">Nothing here yet.</p>}
      {threads.map((t) => (
        <button key={t.id} className="thread-row" aria-current={t.id === selectedId} data-unread={t.unreadCount > 0} onClick={() => onSelect(t.id)}>
          <span className="row-top">
            <strong>{t.lead.name || t.lead.email}</strong>
            <time>{when(t.lastMessageAt)}</time>
          </span>
          <span className="row-subject">{t.subject || '(no subject)'}</span>
          <span className="row-snippet">{t.lastSnippet}</span>
          <span className="row-badges">
            {t.needsReply && <span className="badge">Needs reply</span>}
            {t.optOutDetected && <span className="badge warn">Asked to stop</span>}
          </span>
        </button>
      ))}
      {nextCursor && <button className="load-more" onClick={() => load(nextCursor)}>Load more</button>}
    </aside>
  );
}

function ThreadView({ threadId }: { threadId: string }) {
  const [data, setData] = useState<{ thread: ConversationThread; messages: ConversationMessage[] } | null>(null);
  const refresh = () => api(`/threads/${threadId}`).then(setData);

  useEffect(() => {
    refresh();
  }, [threadId]);

  if (!data) return <section className="thread">Loading...</section>;
  const { thread, messages } = data;
  const closed = thread.status === 'closed';

  const toggleStatus = async () => {
    await api(`/threads/${thread.id}`, { method: 'PATCH', body: JSON.stringify({ status: closed ? 'open' : 'closed' }) });
    refresh();
  };

  return (
    <section className="thread">
      <header className="thread-header">
        <div>
          <h2>{thread.subject || '(no subject)'}</h2>
          <p>{thread.lead.name ? `${thread.lead.name} <${thread.lead.email}>` : thread.lead.email}</p>
        </div>
        <button onClick={toggleStatus}>{closed ? 'Reopen' : 'Close'}</button>
      </header>
      <div className="messages">
        {messages.map((m) => <Message key={m.id} message={m} />)}
      </div>
      <ReplyBox thread={thread} messages={messages} onSent={refresh} />
    </section>
  );
}

const SYSTEM_LABELS: Record<string, string> = {
  original: 'Your email',
  auto_reply: 'Automatic reply',
  bounce: 'Delivery failure',
  read_receipt: 'Read receipt',
};

function Message({ message }: { message: ConversationMessage }) {
  const system = SYSTEM_LABELS[message.kind];
  if (system) {
    const label = message.outOfOffice ? 'Out of office' : system;
    return (
      <details className="system-message">
        <summary>{label}: {message.subject || message.snippet}</summary>
        {message.hasHtml ? <EmailBody messageId={message.id} /> : <p className="text">{message.text}</p>}
      </details>
    );
  }

  const fromTeam = message.kind === 'staff_reply';
  return (
    <article className={fromTeam ? 'bubble from-team' : 'bubble'}>
      <header>
        <strong>{message.from.name || message.from.email}</strong>
        {message.recipient?.role === 'cc' && <span className="badge">CC</span>}
        {message.participant === 'external' && <span className="badge">Forwarded</span>}
        <time>{when(message.occurredAt)}</time>
      </header>
      {message.senderAuth === 'failed' && (
        <p className="warn">We could not verify this sender. Be careful with links and attachments.</p>
      )}
      {message.optOut.detected && <p className="warn">Asked to stop receiving emails</p>}
      {message.hasHtml ? <EmailBody messageId={message.id} /> : <p className="text">{message.newText || message.text}</p>}
      {message.attachments.filter((a) => !a.inline).map((a) => (
        <a key={a.id} className="attachment" href={`/api/inbox/messages/${message.id}/attachments/${a.id}`}>
          {a.filename} ({Math.ceil(a.size / 1024)} KB)
        </a>
      ))}
    </article>
  );
}

function ReplyBox({ thread, messages, onSent }: {
  thread: ConversationThread;
  messages: ConversationMessage[];
  onSent: () => void;
}) {
  const [text, setText] = useState('');
  const [draftId, setDraftId] = useState(() => crypto.randomUUID());
  const [sending, setSending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const lastReply = [...messages].reverse().find((m) => m.kind === 'reply');
  const to = lastReply?.from.email || thread.lead.email;
  const from = thread.senderName ? `${thread.senderName} <${thread.fromEmail}>` : thread.fromEmail;

  const send = async () => {
    setSending(true);
    setError(null);
    try {
      await api(`/threads/${thread.id}/replies`, { method: 'POST', body: JSON.stringify({ text, draftId }) });
      setText('');
      setDraftId(crypto.randomUUID());
      onSent();
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setSending(false);
    }
  };

  return (
    <footer className="reply-box">
      <small>Replying to {to} from {from}</small>
      <textarea value={text} onChange={(e) => setText(e.target.value)} placeholder={`Reply to ${to}`} rows={4} />
      {error && <p className="warn">{error}</p>}
      <button disabled={!text.trim() || sending} onClick={send}>{sending ? 'Sending...' : 'Send'}</button>
    </footer>
  );
}

A starting point for the styles:

css
.inbox { display: grid; grid-template-columns: 360px 1fr; gap: 16px; height: calc(100vh - 120px); }
.thread-list, .thread { display: flex; flex-direction: column; overflow: auto; border: 1px solid #e5e5e5; border-radius: 10px; }
.thread-row { display: grid; gap: 2px; padding: 10px 12px; text-align: left; border: 0; border-bottom: 1px solid #f0f0f0; background: none; }
.thread-row[aria-current='true'] { background: #f3f6ff; }
.thread-row[data-unread='true'] strong, .thread-row[data-unread='true'] .row-subject { font-weight: 700; }
.row-top { display: flex; justify-content: space-between; }
.row-snippet { color: #666; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.messages { flex: 1; overflow: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; }
.bubble { max-width: 85%; border: 1px solid #e5e5e5; border-radius: 10px; padding: 10px; }
.bubble.from-team { align-self: flex-end; background: #f5faea; }
.quote-toggle { margin-top: 4px; padding: 0 8px; border-radius: 6px; }
.warn { color: #b45309; }
.reply-box { display: grid; gap: 8px; padding: 12px; border-top: 1px solid #e5e5e5; }
@media (max-width: 800px) { .inbox { grid-template-columns: 1fr; } }

Step 5: Keep It Current ​

The list above checks for new replies every 30 seconds, which is enough for most teams. For replies within seconds, subscribe a webhook to the reply event and push a message to the open browser over your own realtime channel (WebSocket, server-sent events), which then reloads the list and, if it is open, the conversation. See Sync With Webhooks.

Checklist ​

  • The API key stays on your server; the browser only calls your routes, behind your own login.
  • The list opens on Needs reply and shows who, when, subject, the latest message, an unread dot and badges.
  • Messages run oldest first. Your team's replies sit on the right, the other person's on the left.
  • Each email shows displayHtml first, with "•••" for the trimmed history, inside a sandboxed iframe on a white background.
  • Your original email and automatic replies are collapsed rows, not full bubbles.
  • Unverified senders and requests to stop are flagged where your team will see them.
  • Replies carry a draftId as the idempotency key, so a retried send goes out once.
  • A conversation belongs to one email. To show one timeline per person, group conversations by lead.email.

Released under the MIT License.