Skip to content

Show Email Logs in Your Application ​

Outbound keeps a log of every email you send: who got it, what happened to it, and when. This guide shows how to put that log in front of your team inside your own application, as a Logs page that works the way the one in the Outbound dashboard does: a table of sent emails with filters and pages, and a preview of any email you open.

The examples use Express on the server and React in the browser. The same steps work with any stack. For every parameter and field, see the Email reference. For status updates as they happen, see Tracking Email Status via Webhooks.

text
┌────────────────────────────────────────────────────────────────────────────┐
│ Status [Any ▾]   Recipient [_______________]   Sender [_______________]    │
│ Subject [__________________]   Dates [Jan 1, 2026] to [Today]   [Clear]    │
├────────────────────────────────────────────────────────────────────────────┤
│ Recipient                 Subject                    Status      Sent      │
│ riya@example.com          Your application is comp.  [delivered] 5 Nov     │
│ arjun@example.com +1      Interview slot             [bounced]   4 Nov     │
│ meera@example.com         Fee receipt                [dropped]   3 Nov     │
├────────────────────────────────────────────────────────────────────────────┤
│ Showing 1-10 of 1,234      < 1  2  3  ...  124 >      Per page [10 ▾]      │
└────────────────────────────────────────────────────────────────────────────┘

┌────────────────────────────────────────────────────────────────────────────┐
│ Preview                                                     [Close]        │
│ From     Your Team <hello@example.com>                                     │
│ To       riya@example.com                                                  │
│ Subject  Your application is complete                                      │
│ Sent     5 Nov, 10:42 AM                                                   │
│                                                                            │
│ ┌────────────────────────────────────────────────────────────────────────┐ │
│ │ The email, exactly as it was sent, in a sandboxed frame.               │ │
│ │ Links, images and layout are the real ones.                            │ │
│ └────────────────────────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────────────────────────┘

The Two Calls ​

Your page uses two SDK methods. They do different jobs.

CallReturnsUsed for
outbound.email.listLogs(params)One page of log rows: addresses, subject, status and times. No email body.The table, its filters and its pages. Runs on every change.
outbound.email.getMessageContent(messageId)One email: subject, addresses, htmlBody and textBody.The preview. Runs only when someone opens one email.

The list stays small and fast because it never carries email bodies. The body is fetched only for the one email someone opens.

Before You Start ​

  1. Create an API key in the dashboard under API Keys. Keep it secret: it can read every log on your account.
  2. Use Node.js 18 or later, and install the SDK:
bash
npm install @masters-union/outbound-sdk

An email appears in the logs once Outbound queues it, usually within seconds of your send call. A send to a contact list adds its emails as the list is processed. Status changes (delivered, opened, clicked and so on) appear as they happen.

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 log and every email on your account. The logs include your recipients' email addresses, so the key stays on your server. The browser talks to two routes on your server, your server checks that the person is allowed to see the logs, and only then does it call the SDK. Give these routes to staff who are allowed to see recipients' addresses and nobody else.

Step 1: Add Log Routes to Your Server ​

Two routes cover the page. 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 { Outbound, BadRequestError, NotFoundError, RateLimitError } from '@masters-union/outbound-sdk';
import type { EmailStatus } from '@masters-union/outbound-sdk';

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

// Your own login check. Only staff who may see recipients' addresses get past it.
app.use('/api/email-logs', requireStaff);

const text = (value: unknown) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined);

// The log table. Only the fields listed here reach the SDK.
app.get('/api/email-logs', async (req, res) => {
  const cursor = text(req.query.cursor);
  const status = text(req.query.status)?.split(',').map((s) => s.trim()).filter(Boolean) as EmailStatus[] | undefined;
  const { logs, pagination, dateRange } = await outbound.email.listLogs({
    page: cursor ? undefined : Number(text(req.query.page) ?? 1),
    pageSize: Number(text(req.query.pageSize) ?? 10),
    cursor,
    status: status?.length ? status : undefined,
    toEmail: text(req.query.toEmail),
    fromEmail: text(req.query.fromEmail),
    subject: text(req.query.subject),
    messageId: text(req.query.messageId),
    campaignId: text(req.query.campaignId),
    startDate: text(req.query.startDate),
    endDate: text(req.query.endDate),
    tz: text(req.query.tz),
  });
  res.json({ logs, pagination, dateRange });
});

// One email's content, loaded only when someone opens it.
app.get('/api/email-logs/:messageId/content', async (req, res) => {
  const { subject, fromEmail, senderName, toEmail, ccEmail, bccEmail, htmlBody, textBody, sentAt } =
    await outbound.email.getMessageContent(req.params.messageId);
  res.json({ subject, fromEmail, senderName, toEmail, ccEmail, bccEmail, htmlBody, textBody, sentAt });
});

app.use((err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
  if (err instanceof BadRequestError) {
    return res.status(400).json({ error: err.message, param: err.details?.param, code: err.details?.code });
  }
  if (err instanceof NotFoundError) {
    return res.status(404).json({ error: 'Email not found.' });
  }
  if (err instanceof RateLimitError) {
    res.set('Retry-After', String(err.retryAfter ?? 60));
    return res.status(429).json({ error: 'Too many requests. Try again shortly.' });
  }
  console.error('Email logs request failed', err);
  res.status(500).json({ error: 'Something went wrong. Try again.' });
});

Register the error handler after your routes. The query_timeout code is passed through so the page can ask the user to narrow the search (see Step 4).

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.email.listLogs(params, { apiKey }) and outbound.email.getMessageContent(messageId, { apiKey }). See Configuration.

Step 2: Lay Out the Table ​

Show one row per email. The table has four columns in the sketch above. Sender and Campaign are useful extras if your team needs them.

ColumnFieldNotes
RecipienttoEmailAdd a grey "+N" when ccEmail or bccEmail lists more addresses.
SendersenderName, or fromEmail when there is no nameOptional column.
SubjectsubjectShow "(no subject)" when it is null.
StatusstatusA coloured badge (see the table below). Put errorMessage in a tooltip for bounced, failed and dropped emails.
UnsubscribedunsubscribeWhen it is set, show an "Unsubscribed" badge next to the status. The status still shows the delivery result.
CampaigncampaignIdOptional column. Show it only when it is not null.
SentsentAt, or createdAt before the email is sentShow it in the user's time zone.

The status badge colours:

StatusMeaningColour
queuedWaiting to sendNeutral
processingBeing sentNeutral
cancelledCancelled before sendingNeutral
sentAccepted for delivery, waiting for the receiving serverBlue
deliveredAccepted by the recipient's mail serverGreen
openedThe recipient opened the emailGreen
clickedThe recipient clicked a linkGreen
bouncedRejected by the recipient's server. See errorMessage.Red
complainedThe recipient marked it as spamRed
failedCould not be sent. See errorMessage.Red
droppedNot sent because the address is suppressed or invalid. errorMessage says why, for example "Suppressed: bounce".Amber

Step 3: Add Pagination ​

listLogs returns a pagination object. Use it to draw the pager:

  • Page buttons come from pagination.page and pagination.totalPages.
  • Show "Showing 11-20 of 1,234" with the page's first and last row numbers and totalRecords.
  • When totalRecordsCapped is true, show "10,000+" instead of the number. Counting stops at 10,000, and totalPages is the number of pages you can reach.
  • Disable Previous when !hasPreviousPage, and Next when !hasNextPage. hasNextPage is true only if the next page can be requested. More logs can exist even when it is false, for example past the 10,000th row.
  • When totalRecordsCapped is true and hasNextPage is false, tell the user to narrow the date range to see the rest.

Page numbers with gaps keep the pager short. This helper returns the numbers to draw, with '...' for each gap:

ts
function pageItems(current: number, total: number): (number | string)[] {
  const pages = [...new Set([1, total, current - 1, current, current + 1])]
    .filter((p) => p >= 1 && p <= total)
    .sort((a, b) => a - b);
  return pages.flatMap((p, i) => (i > 0 && p - pages[i - 1] > 1 ? ['...', p] : [p]));
}

Keep the list stable while paging

Logs are newest first, and new mail arrives all the time. Without a fixed end point, a row can move from page 1 to page 2 between two clicks, and the user sees it twice or misses it. Take a snapshot of "now" when the user first loads the page or changes a filter, and send that same endDate with every page request. The Step 6 component does this.

Page size is a choice of 10, 25, 50 or 100. Change it back to page 1.

Load more instead of pages

For an infinite list or a "Load more" button, use cursor instead of page. Send the same filters and endDate as before, and leave out page. Each response carries pagination.nextCursor, which is null when there is nothing more to load.

tsx
async function loadNextPage(cursor: string) {
  const params = new URLSearchParams(query);
  params.delete('page');
  params.set('cursor', cursor);
  const body: LogsResponse = await fetch(`/api/email-logs?${params}`).then((res) => res.json());
  setLogs((current) => [...current, ...body.logs]);
  setCursor(body.pagination.nextCursor);
}

query is the query string built in Step 6, and logs and cursor are state you keep for the list. The Load more button calls loadNextPage(cursor) while cursor is set.

Step 4: Add Filters ​

Put these above the table:

FilterSent asNotes
StatusstatusA multi-select. Sent as a comma list, for example bounced,complained.
RecipienttoEmail
SenderfromEmail
SubjectsubjectWait 300 ms after the user stops typing before searching.
Message IDmessageIdUse it to find one email from its ID.
DatesstartDate, endDate, tzTwo date pickers. tz is the user's time zone, so a date means the user's day.

Every change to a filter does three things: it goes back to page 1, it takes a new endDate snapshot, and it runs the search again.

Addresses match in one of two ways. A complete address, such as riya@example.com, matches exactly, ignoring case. Anything else matches part of the address, so example.com finds every recipient at that domain. A complete address is the fastest search.

With no dates chosen, Outbound searches the last 90 days. The response's dateRange shows the window it actually used, so show it. When no dates were chosen, show "Showing the last 90 days". Otherwise show the dateRange as "Showing 1 Oct 2026 to 5 Nov 2026". When the search finds nothing, say what was searched, so the user knows whether to widen the dates.

If a search is too broad, the server returns a 400 with code: 'query_timeout'. Ask the user to narrow the date range. The Step 6 component shows this message.

Step 5: Show an Email When Someone Clicks a Row ​

Fetch the content when the user opens a row, not before. The table never needs bodies, so the list stays fast.

Render htmlBody in a sandboxed iframe:

tsx
<iframe sandbox="" srcDoc={htmlBody} title="Email preview" />

The HTML is the email as it was sent, so the preview shows what the recipient saw. The empty sandbox attribute stops scripts, forms and pop-ups from running inside the preview, so viewing an email cannot act on the recipient's behalf. Never put htmlBody into your page with innerHTML, because the email's styles and scripts would then run in your application.

Links in the preview

The email's links are the real ones, including the recipient's unsubscribe link in the footer. With sandbox="" a click can only load a page inside the frame. Unsubscribing needs a form to be submitted, which the sandbox blocks, so a click in the preview cannot unsubscribe the recipient. Keep the attribute empty: adding allow-forms, allow-scripts or allow-popups removes that protection.

When htmlBody is null, show textBody in a <pre>. When both are null, show "The content of this email is no longer available." Outbound keeps email content for a limited time (90 days by default) while the log stays, so older emails can have no content.

Show a header above the email with From (senderName <fromEmail>), To, CC, BCC when set, Subject and Sent.

Step 6: Put It Together ​

This component is the whole page. It holds the filters, page, page size and the endDate snapshot in state. It loads the table from /api/email-logs and the preview from /api/email-logs/:messageId/content. Paste it into a file in your React app. It uses no UI library.

tsx
import { useEffect, useState } from 'react';

type Filters = {
  status: string[];
  toEmail: string;
  fromEmail: string;
  subject: string;
  messageId: string;
  startDate: string;
  endDate: string;
};

type Log = {
  messageId: string;
  status: string;
  errorMessage: string | null;
  fromEmail: string;
  senderName: string | null;
  toEmail: string;
  ccEmail: string | null;
  bccEmail: string | null;
  subject: string | null;
  createdAt: string;
  sentAt: string | null;
  unsubscribe: { reasonLabel: string } | null;
};

type LogsResponse = {
  logs: Log[];
  pagination: {
    page: number;
    pageSize: number;
    totalRecords: number;
    totalRecordsCapped: boolean;
    totalPages: number;
    hasNextPage: boolean;
    hasPreviousPage: boolean;
    nextCursor: string | null;
  };
  dateRange: { startDate: string | null; endDate: string | null };
};

type Content = {
  subject: string | null;
  fromEmail: string;
  senderName: string | null;
  toEmail: string;
  ccEmail: string | null;
  bccEmail: string | null;
  htmlBody: string | null;
  textBody: string | null;
  sentAt: string | null;
};

const EMPTY_FILTERS: Filters = { status: [], toEmail: '', fromEmail: '', subject: '', messageId: '', startDate: '', endDate: '' };
const STATUSES = ['queued', 'processing', 'sent', 'delivered', 'opened', 'clicked', 'bounced', 'complained', 'failed', 'cancelled', 'dropped'];
const TONE: Record<string, string> = {
  queued: 'neutral', processing: 'neutral', cancelled: 'neutral',
  sent: 'blue',
  delivered: 'green', opened: 'green', clicked: 'green',
  bounced: 'red', failed: 'red', complained: 'red',
  dropped: 'amber',
};
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

const formatTime = (iso: string | null) => (iso ? new Date(iso).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) : '-');
const formatDay = (iso: string) => new Date(iso).toLocaleDateString([], { day: 'numeric', month: 'short', year: 'numeric' });
const countAddresses = (list: string | null) => (list ? list.split(',').filter((a) => a.trim()).length : 0);
const extraCount = (log: Log) => countAddresses(log.ccEmail) + countAddresses(log.bccEmail);

function pageItems(current: number, total: number): (number | string)[] {
  const pages = [...new Set([1, total, current - 1, current, current + 1])]
    .filter((p) => p >= 1 && p <= total)
    .sort((a, b) => a - b);
  return pages.flatMap((p, i) => (i > 0 && p - pages[i - 1] > 1 ? ['...', p] : [p]));
}

function useDebounced<T>(value: T, delay: number) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);
  return debounced;
}

function buildQuery(filters: Filters, page: number, pageSize: number, snapshot: string) {
  const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize), endDate: filters.endDate || snapshot });
  if (filters.status.length) params.set('status', filters.status.join(','));
  for (const key of ['toEmail', 'fromEmail', 'subject', 'messageId', 'startDate'] as const) {
    if (filters[key]) params.set(key, filters[key]);
  }
  if (filters.startDate || filters.endDate) params.set('tz', timeZone);
  return params.toString();
}

export function EmailLogsPage() {
  const [filters, setFilters] = useState<Filters>(EMPTY_FILTERS);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [snapshot, setSnapshot] = useState(() => new Date().toISOString());
  const [selected, setSelected] = useState<string | null>(null);
  const [data, setData] = useState<LogsResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const query = useDebounced(buildQuery(filters, page, pageSize, snapshot), 300);

  useEffect(() => {
    const controller = new AbortController();
    setLoading(true);
    setError(null);
    fetch(`/api/email-logs?${query}`, { signal: controller.signal })
      .then(async (res) => {
        const body = await res.json().catch(() => ({}));
        if (!res.ok) throw Object.assign(new Error(body.error ?? 'Could not load the logs.'), { code: body.code });
        setData(body);
      })
      .catch((err) => {
        if (controller.signal.aborted) return;
        setError(err.code === 'query_timeout' ? 'That search was too broad. Narrow the date range and try again.' : err.message);
      })
      .finally(() => {
        if (!controller.signal.aborted) setLoading(false);
      });
    return () => controller.abort();
  }, [query]);

  const changeFilters = (patch: Partial<Filters>) => {
    setFilters((current) => ({ ...current, ...patch }));
    setPage(1);
    setSnapshot(new Date().toISOString());
  };

  const logs = data?.logs ?? [];
  const pagination = data?.pagination;
  const from = logs.length ? ((pagination?.page ?? 1) - 1) * (pagination?.pageSize ?? pageSize) + 1 : 0;
  const to = from + logs.length - 1;
  const total = pagination?.totalRecordsCapped ? '10,000+' : pagination?.totalRecords.toLocaleString();
  const windowText = !filters.startDate && !filters.endDate
    ? 'Showing the last 90 days'
    : data ? `Showing ${data.dateRange.startDate ? formatDay(data.dateRange.startDate) : 'the start'} to ${data.dateRange.endDate ? formatDay(data.dateRange.endDate) : 'now'}` : '';

  return (
    <div className="logs">
      <div className="filters">
        <select multiple aria-label="Status" value={filters.status} onChange={(e) => changeFilters({ status: Array.from(e.target.selectedOptions, (o) => o.value) })}>
          {STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
        </select>
        <input placeholder="Recipient" value={filters.toEmail} onChange={(e) => changeFilters({ toEmail: e.target.value })} />
        <input placeholder="Sender" value={filters.fromEmail} onChange={(e) => changeFilters({ fromEmail: e.target.value })} />
        <input placeholder="Subject" value={filters.subject} onChange={(e) => changeFilters({ subject: e.target.value })} />
        <input placeholder="Message ID" value={filters.messageId} onChange={(e) => changeFilters({ messageId: e.target.value })} />
        <input type="date" aria-label="From date" value={filters.startDate} onChange={(e) => changeFilters({ startDate: e.target.value })} />
        <input type="date" aria-label="To date" value={filters.endDate} onChange={(e) => changeFilters({ endDate: e.target.value })} />
        <button onClick={() => changeFilters(EMPTY_FILTERS)}>Clear</button>
      </div>
      <p className="window">{windowText}</p>

      {error && <p className="error">{error}</p>}
      {loading && !data && <p>Loading...</p>}
      {data && !loading && logs.length === 0 && (
        <p className="empty">No emails match these filters. {windowText || 'Showing the last 90 days'}.</p>
      )}

      {logs.length > 0 && (
        <table className={loading ? 'is-loading' : ''}>
          <thead>
            <tr><th>Recipient</th><th>Subject</th><th>Status</th><th>Sent</th></tr>
          </thead>
          <tbody>
            {logs.map((log) => (
              <tr key={log.messageId} onClick={() => setSelected(log.messageId)}>
                <td>
                  {log.toEmail}
                  {extraCount(log) > 0 && <span className="muted"> +{extraCount(log)}</span>}
                </td>
                <td>{log.subject || '(no subject)'}</td>
                <td>
                  <span className={`badge tone-${TONE[log.status] ?? 'neutral'}`} title={log.errorMessage ?? undefined}>{log.status}</span>
                  {log.unsubscribe && <span className="badge tone-neutral">Unsubscribed</span>}
                </td>
                <td>{formatTime(log.sentAt ?? log.createdAt)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      {pagination && (
        <footer className="pager">
          <span>{logs.length ? `Showing ${from}-${to} of ${total}` : ''}</span>
          <button disabled={!pagination.hasPreviousPage} onClick={() => setPage(page - 1)}>Previous</button>
          {pageItems(pagination.page, pagination.totalPages).map((item, i) =>
            item === '...'
              ? <span key={`gap-${i}`}>...</span>
              : <button key={item} aria-current={item === pagination.page} onClick={() => setPage(item as number)}>{item}</button>
          )}
          <button disabled={!pagination.hasNextPage} onClick={() => setPage(page + 1)}>Next</button>
          <select aria-label="Rows per page" value={pageSize} onChange={(e) => { setPageSize(Number(e.target.value)); setPage(1); }}>
            {[10, 25, 50, 100].map((n) => <option key={n} value={n}>{n} per page</option>)}
          </select>
        </footer>
      )}
      {pagination?.totalRecordsCapped && !pagination.hasNextPage && (
        <p className="warn">Only the first 10,000 results can be paged through. Narrow the date range to see the rest.</p>
      )}

      {selected && <EmailPreview messageId={selected} onClose={() => setSelected(null)} />}
    </div>
  );
}

function EmailPreview({ messageId, onClose }: { messageId: string; onClose: () => void }) {
  const [content, setContent] = useState<Content | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    setContent(null);
    setError(null);
    fetch(`/api/email-logs/${encodeURIComponent(messageId)}/content`, { signal: controller.signal })
      .then(async (res) => {
        const body = await res.json().catch(() => ({}));
        if (!res.ok) throw new Error(body.error ?? 'Could not load this email.');
        setContent(body);
      })
      .catch((err) => {
        if (!controller.signal.aborted) setError(err.message);
      });
    return () => controller.abort();
  }, [messageId]);

  if (error) return <aside className="preview"><p className="error">{error}</p><button onClick={onClose}>Close</button></aside>;
  if (!content) return <aside className="preview"><p>Loading...</p></aside>;

  return (
    <aside className="preview">
      <header>
        <button onClick={onClose}>Close</button>
        <dl>
          <dt>From</dt><dd>{content.senderName ? `${content.senderName} <${content.fromEmail}>` : content.fromEmail}</dd>
          <dt>To</dt><dd>{content.toEmail}</dd>
          {content.ccEmail && <><dt>CC</dt><dd>{content.ccEmail}</dd></>}
          {content.bccEmail && <><dt>BCC</dt><dd>{content.bccEmail}</dd></>}
          <dt>Subject</dt><dd>{content.subject || '(no subject)'}</dd>
          <dt>Sent</dt><dd>{formatTime(content.sentAt)}</dd>
        </dl>
      </header>
      {content.htmlBody ? (
        <iframe sandbox="" srcDoc={content.htmlBody} title="Email preview" className="preview-frame" />
      ) : content.textBody ? (
        <pre>{content.textBody}</pre>
      ) : (
        <p>The content of this email is no longer available.</p>
      )}
    </aside>
  );
}

A starting point for the styles:

css
.badge { padding: 2px 8px; border-radius: 999px; font-size: 12px; margin-right: 4px; }
.tone-neutral { background: #eee; color: #444; }
.tone-blue { background: #e0ecff; color: #1d4ed8; }
.tone-green { background: #dcfce7; color: #15803d; }
.tone-red { background: #fee2e2; color: #b91c1c; }
.tone-amber { background: #fef3c7; color: #b45309; }
.muted { color: #888; }
.pager { display: flex; gap: 6px; align-items: center; margin-top: 12px; }
.pager button[aria-current='true'] { font-weight: 700; }
.preview-frame { width: 100%; height: 60vh; border: 0; background: #fff; }
.preview pre { white-space: pre-wrap; }
.warn { color: #b45309; }
.error { color: #b91c1c; }

Count Outcomes for a Subject or Campaign ​

To count outcomes, such as how many emails were delivered, opened or bounced, don't page through the logs. Call email.getStats() once. It counts on the server and returns totals and rates for the emails that match your filters. This needs SDK 1.3.4 or later. See Get Email Stats.

ts
const stats = await outbound.email.getStats({
  subject: 'Your application is complete',
  startDate: '2026-11-01',
  endDate: '2026-11-30',
  tz: 'Asia/Kolkata',
});

console.log(`${stats.sent} sent, ${stats.delivered} delivered, ${stats.openRate}% opened`);

Use listLogs() or listAllLogs() when you need the individual emails. Use getStats() when you need the numbers.

Exporting Every Log ​

For a file with every matching log, use listAllLogs. It is an async generator: it reads 100 logs per request and fetches the next 100 with a cursor as you loop. It respects the rate limit (120 log requests per minute per account), and the SDK retries a rate-limited request automatically.

Without startDate, the search covers the last 90 days. Pass a date to go further back.

ts
import { createWriteStream } from 'node:fs';
import { Outbound } from '@masters-union/outbound-sdk';

const outbound = new Outbound({ apiKey: process.env.OUTBOUND_API_KEY });
const out = createWriteStream('bounced-and-complained.csv');
const columns = ['createdAt', 'messageId', 'status', 'toEmail', 'fromEmail', 'subject', 'errorMessage'] as const;
const cell = (value: unknown) => `"${String(value ?? '').replace(/"/g, '""')}"`;

out.write(`${columns.join(',')}\n`);
for await (const log of outbound.email.listAllLogs({ startDate: '2026-01-01', status: ['bounced', 'complained'] })) {
  out.write(`${columns.map((column) => cell(log[column])).join(',')}\n`);
}
out.end();

Run it on your server, not in the browser. Each row is one email, so a large export can take a while. Keep the file on your server and send it to staff through your own download route.

Checklist ​

  • The API key stays on your server. The browser only calls your two routes, behind your own login.
  • The routes are open only to staff who may see recipients' addresses.
  • The server builds SDK parameters only from an allowlist of query fields.
  • Each filter change returns to page 1 and takes a new endDate snapshot, so pages stay stable.
  • Counts show "10,000+" when totalRecordsCapped is true, and the user is told to narrow the dates on the last reachable page.
  • Email bodies load only when someone opens a row, and they render in a sandboxed iframe with sandbox="".
  • Emails with no content show the text fallback or the "no longer available" message.
  • SDK errors map to clear responses: 400 with the bad parameter, 404, 429 with Retry-After, and 500 for anything else.
  • Apps with several customers pass each customer's key per call.

Released under the MIT License.