Skip to content

Email ​

Send single and bulk emails, and track delivery status by job ID.

All examples assume you've set the API key in the constructor. For multi-tenant usage, pass { apiKey } as the last argument to any method. See Configuration.

Send Single Email ​

Send one email to one recipient.

ts
const result = await outbound.email.send({
  toEmail: 'user@example.com',
  fromEmail: 'noreply@yourcompany.com',
  emailSubject: 'Your order has shipped',
  htmlBody: '<h1>Order #1234 Shipped</h1><p>Your package is on its way.</p>',
  textBody: 'Order #1234 Shipped. Your package is on its way.',
  senderName: 'YourCompany',
  replyTo: 'support@yourcompany.com',
});

Full Parameters ​

ts
await outbound.email.send({
  // Required
  toEmail: 'user@example.com',
  fromEmail: 'noreply@yourcompany.com',  // must be a verified domain
  emailSubject: 'Subject line',
  htmlBody: '<h1>Email content</h1>',

  // Optional
  textBody: 'Plain text fallback',
  senderName: 'Display Name',            // shows as "Display Name <noreply@...>"
  replyTo: 'support@yourcompany.com',
  ccEmail: 'cc@example.com',
  bccEmail: 'bcc@example.com',
  priority: 'high',                       // 'critical'|'urgent'|'high'|'normal'|'low'|'deferred'|'backlog' (default: 'normal')
  idempotencyKey: 'order-shipped-1234',   // prevents duplicate sends
  metadata: { orderId: '1234', userId: 'u_abc' },
  headers: { 'X-Custom-Header': 'value' },
  tracking: { opens: true, clicks: true },
  attachments: [
    {
      filename: 'invoice.pdf',
      content: 'base64-encoded-content-here',
      contentType: 'application/pdf',
    },
  ],
});

Parameters Reference ​

FieldTypeRequiredDescription
toEmailstringYesRecipient email address
fromEmailstringYesSender email — must be a verified domain assigned to your tenant
emailSubjectstringYesEmail subject line
htmlBodystringYesHTML email body
textBodystringNoPlain text alternative (recommended for deliverability)
ampBodystringNoAMP for Email version. fromEmail must be one of your AMP addresses. Gmail, Yahoo Mail and Mail.ru show it once they have approved that address, and htmlBody stays the fallback. See Sending AMP Emails
senderNamestringNoDisplay name shown to recipient
replyTostringNoReply-to email address
ccEmailstringNoCC recipient
bccEmailstringNoBCC recipient
prioritystringNo'critical', 'urgent', 'high', 'normal' (default), 'low', 'deferred', or 'backlog'. Unrecognized values are treated as 'normal'.
idempotencyKeystringNoUnique key to prevent duplicate sends — expires after 24 hours (see below)
campaignIdstringNoTag this email as part of a campaign — enables bulk cancellation via email.cancel()
metadataobjectNoCustom key-value pairs stored with the email
headersobjectNoCustom email headers
trackingobjectNoOpen and click tracking configuration
attachmentsAttachment[]NoFile attachments (max 25MB each, 25MB total)
captureRepliesbooleanNoCollect replies to this email as a conversation. Default false. See Capturing Replies
replyDomainstringNoWhich of your reply domains to use instead of your default. Requires captureReplies: true
createThreadbooleanNoOpen the conversation as soon as the email is sent, so emails nobody has replied to are listed too. Default false. Requires captureReplies: true

Response ​

ts
{
  message: 'Email queued successfully',
  jobId: '550e8400-e29b-41d4-a716-446655440000',
  messageId: '660e8400-e29b-41d4-a716-446655440001'
}
FieldDescription
jobIdUnique job ID — use this to check delivery status
messageIdUnique message ID for this specific recipient
captureRepliestrue when replies to this email are captured. Absent otherwise
replyDomainThe reply domain used. Present only with captureReplies
createThreadtrue or false: whether the conversation is opened at send. Present only with captureReplies

Possible Errors ​

ErrorStatusCause
BadRequestError400Missing required fields, invalid email format
AuthenticationError401Invalid or missing API key
ForbiddenError403Domain not verified, tenant suspended
ConflictError409Idempotency key is currently being processed by another request
OutboundError422ampBody is set and fromEmail is not one of your AMP addresses (details.availableAmpAddresses lists them). See List AMP Addresses
RateLimitError429Per-second rate limit exceeded, or the global AWS SES daily sending quota is exhausted ("Daily Quota Exhausted (X/Y). Try again later.")

Idempotency ​

Use idempotencyKey to safely retry without sending duplicate emails. Keys are scoped per tenant and expire after 24 hours — after that, the same key can be reused.

ts
// First call — email is queued
const result1 = await outbound.email.send({
  toEmail: 'user@example.com',
  fromEmail: 'noreply@company.com',
  emailSubject: 'Order Confirmation',
  htmlBody: '<h1>Order confirmed</h1>',
  idempotencyKey: 'order-confirm-1234',
});

// Second call with same key — returns the exact cached response, no duplicate sent
const result2 = await outbound.email.send({
  toEmail: 'user@example.com',
  fromEmail: 'noreply@company.com',
  emailSubject: 'Order Confirmation',
  htmlBody: '<h1>Order confirmed</h1>',
  idempotencyKey: 'order-confirm-1234',
});

// result1.jobId === result2.jobId ✓
// result2.duplicate === true

How it works

  • The key is locked when the request starts processing. If a second request arrives with the same key while the first is still in-flight, it returns 409 Conflict.
  • Once the first request completes, subsequent calls return the exact same response (same jobId, messageId) with duplicate: true.
  • After 24 hours, the key expires and can be reused for a new send.
  • If the original request fails (validation error, SES quota exhausted, etc.), the key is released so you can retry immediately.
  • Keys are stored in Postgres (durable) and cached in Redis for fast lookups. Redis eviction under memory pressure is safe — the system falls back to Postgres automatically.

Generating Good Idempotency Keys ​

The key should be deterministic — the same logical send should always produce the same key. This way, retries automatically deduplicate without you tracking state.

Single email — combine the purpose + recipient:

ts
import { createHash } from 'crypto';

// Transactional: one email type per order
const key = createHash('sha256')
  .update(`order-confirmation:${orderId}:${recipientEmail}`)
  .digest('hex');

await outbound.email.send({
  toEmail: recipientEmail,
  fromEmail: 'noreply@company.com',
  emailSubject: 'Order Confirmed',
  htmlBody: '<h1>Thanks for your order</h1>',
  idempotencyKey: key,
});

Bulk email — use the batch identity (a single key covers the whole batch):

ts
// Campaign: one key for the entire batch
const key = createHash('sha256')
  .update(`newsletter:march-2026:batch-1`)
  .digest('hex');

await outbound.email.bulk({
  fromEmail: 'news@company.com',
  emailSubject: 'March Newsletter',
  idempotencyKey: key,
  emails: recipients,
});

Same key = same request

The idempotency key represents the entire API call, not individual recipients. If you send 100 emails with key "abc", then call again with 300 emails and the same key "abc", the second call returns the cached response from the first — it does not send to the extra 200.

Example: Bulk Sends for a Campaign ​

Suppose you're running campaign COM-0001 and sending to 1,200 recipients. Since the bulk API accepts max 500 per call, you'd split into 3 batches. Each batch needs its own idempotency key:

ts
import { createHash } from 'crypto';

const campaignId = 'COM-0001';
const allRecipients = [ /* 1,200 recipients */ ];

// Split into batches of 500
const batchSize = 500;
const batches = [];
for (let i = 0; i < allRecipients.length; i += batchSize) {
  batches.push(allRecipients.slice(i, i + batchSize));
}

// Send each batch with a unique, deterministic key
for (let i = 0; i < batches.length; i++) {
  const key = createHash('sha256')
    .update(`${campaignId}:batch-${i + 1}`)
    .digest('hex');
  // COM-0001:batch-1 → "a3f8b2..."
  // COM-0001:batch-2 → "7c1d4e..."
  // COM-0001:batch-3 → "9e2f1a..."

  await outbound.email.bulk({
    fromEmail: 'campaigns@yourcompany.com',
    emailSubject: 'Exclusive Offer from YourCompany',
    senderName: 'YourCompany',
    idempotencyKey: key,
    emails: batches[i].map(r => ({
      toEmail: r.email,
      htmlBody: `<h1>Hi ${r.name}</h1><p>Your exclusive offer...</p>`,
    })),
  });
}

// Safe to retry the entire loop — batches that already succeeded
// will return the cached response with duplicate: true

Why this works:

  • Each batch gets a deterministic key based on campaign + batch number
  • If your process crashes after batch 2, you can restart the loop — batches 1 and 2 return instantly as duplicates, batch 3 sends normally
  • The same campaign can never accidentally double-send a batch within 24 hours

Attachments ​

ts
import { readFileSync } from 'fs';

await outbound.email.send({
  toEmail: 'user@example.com',
  fromEmail: 'noreply@company.com',
  emailSubject: 'Your Invoice',
  htmlBody: '<p>Please find your invoice attached.</p>',
  attachments: [
    {
      filename: 'invoice-march-2026.pdf',
      content: readFileSync('./invoice.pdf').toString('base64'),
      contentType: 'application/pdf',
    },
    {
      filename: 'logo.png',
      content: readFileSync('./logo.png').toString('base64'),
      contentType: 'image/png',
    },
  ],
});

Attachment Limits

  • Max 25MB per individual attachment
  • Max 25MB total per email
  • Content must be base64 encoded

Both limits are measured on the file's real size, not on the base64 you send, so they match the size your operating system reports. A single file may use the whole 25MB, which means the total is the limit that actually binds a send: two 20MB files are rejected even though each one is individually fine.


Send Bulk Emails ​

Send up to 500 emails in a single API call. Each recipient can have a different HTML body and subject.

ts
const result = await outbound.email.bulk({
  fromEmail: 'noreply@yourcompany.com',
  emailSubject: 'Monthly Newsletter',
  senderName: 'YourCompany',
  replyTo: 'newsletter@yourcompany.com',
  priority: 'low',                          // 'critical'|'urgent'|'high'|'normal'|'low'|'deferred'|'backlog' (default: 'normal')
  emails: [
    {
      toEmail: 'alice@example.com',
      htmlBody: '<h1>Hi Alice</h1><p>Your personalized content here.</p>',
    },
    {
      toEmail: 'bob@example.com',
      htmlBody: '<h1>Hi Bob</h1><p>Different content for Bob.</p>',
      subject: 'Bob, check this out!',  // overrides emailSubject for this recipient
    },
    {
      toEmail: 'charlie@example.com',
      htmlBody: '<h1>Hi Charlie</h1>',
      metadata: { segment: 'vip' },
    },
  ],
});

Parameters ​

FieldTypeRequiredDescription
fromEmailstringYesSender email (verified domain)
emailSubjectstringYesDefault subject for all recipients
emailsBulkEmailRecipient[]YesArray of recipients (max 500)
senderNamestringNoDisplay name
replyTostringNoReply-to address
ampBodystringNoShared AMP version for a mail-merge batch, rendered with each recipient's variables. Needs a shared htmlBody, and fromEmail must be one of your AMP addresses. See Sending AMP Emails
prioritystringNo'critical', 'urgent', 'high', 'normal' (default), 'low', 'deferred', or 'backlog' — queue priority for the whole batch, draining highest-urgency first in that order. 'critical'/'urgent'/'high' bypass send pacing; 'normal' and below are paced. Unrecognized values are treated as 'normal'. Use 'backlog'/'deferred' for large backfill campaigns so transactional sends jump ahead.
idempotencyKeystringNoPrevents duplicate bulk sends — expires after 24 hours
campaignIdstringNoTag this batch as part of a campaign — enables bulk cancellation via email.cancel()
captureRepliesbooleanNoCollect replies to every email in the batch as conversations. Default false. See Capturing Replies
replyDomainstringNoWhich of your reply domains to use instead of your default. Requires captureReplies: true
createThreadbooleanNoOpen the conversation as soon as the email is sent, so emails nobody has replied to are listed too. Default false. Requires captureReplies: true

Routing campaigns across vendors? See Global Quota for the full check → send → fall back recipe.

Recipient Object ​

FieldTypeRequiredDescription
toEmailstringYesRecipient email address
htmlBodystringYesHTML body for this specific recipient
subjectstringNoOverride the default emailSubject for this recipient
textBodystringNoPlain text alternative
ampBodystringNoAMP version for this recipient. A recipient with its own htmlBody never inherits the shared ampBody
ccEmailstringNoCC recipient
bccEmailstringNoBCC recipient
metadataobjectNoCustom metadata for this recipient

Response ​

ts
{
  message: 'Bulk email queued successfully',
  jobId: '550e8400-e29b-41d4-a716-446655440000',
  recipientCount: 485,      // actual emails that will be sent
  suppressedCount: 12,      // emails filtered out (on suppression list)
  suppressedEmails: [       // which emails were suppressed
    'bounced@example.com',
    'complained@example.com'
  ],
  recipients: [             // per-recipient messageId mapping
    { toEmail: 'a@example.com', messageId: '660e8400-...', status: 'queued' },
    { toEmail: 'bounced@example.com', messageId: '660e8401-...', status: 'suppressed' }
  ],
  duplicatesRemoved: 3      // duplicate toEmails that were deduplicated
}

Duplicate responses are fully populated

When an idempotencyKey is provided and the same request is replayed, the response returns duplicate: true with the same recipients and suppressedEmails as the original. The per-recipient messageId mapping is rebuilt from the job's stored recipient rows (it isn't kept in the idempotency cache), so idempotent retries don't lose it.

On a replay, each recipient's status reflects its live state at replay time — if the worker has already processed the job, you may see sent, delivered, failed, etc. rather than queued. (suppressed recipients stay suppressed.) The first, live response always reports sendable recipients as queued.

Automatic Filtering ​

The platform automatically handles:

  1. Deduplication — If you include the same toEmail twice, only the first occurrence is kept
  2. Suppression filtering — Emails on your suppression list (bounces, complaints, manual suppressions, unsubscribes) are silently removed from the send but persisted as dropped recipient rows on the job, so you can audit them via email.status(jobId)
  3. Quota reservation — Only valid, non-suppressed recipients count against your quota

All-suppressed batches still succeed

If every recipient in a bulk call is on the suppression list, the request still returns 202 Accepted with a jobId. No emails are sent, recipientCount is 0, and every suppressed address is persisted as a dropped row — query the job to see them.

Possible Errors ​

ErrorStatusCause
BadRequestError400Empty emails array, exceeds 500 limit, missing required fields
ForbiddenError403Domain not verified, tenant suspended
ConflictError409Idempotency key is currently being processed by another request
OutboundError422An ampBody (shared or on any recipient) is set and fromEmail is not one of your AMP addresses (details.availableAmpAddresses lists them)
RateLimitError429Exceeded rate limit, or the global AWS SES daily sending quota is exhausted

Capturing Replies ​

Set captureReplies: true to collect the replies to an email as a conversation in Outbound. It works on email.send and on email.bulk, including list sends.

ts
const res = await outbound.email.send({
  toEmail: 'riya@example.com',
  fromEmail: 'admissions@yourcompany.com',
  emailSubject: 'Your application',
  htmlBody: '<p>Hi Riya, reply to this email with any questions.</p>',
  replyTo: 'admissions@yourcompany.com',
  captureReplies: true,
});

console.log(res.captureReplies, res.replyDomain);
// true 'reply.outbound.yourcompany.com'

The email gets a second Reply-To address on your reply domain, the sender's own address name there (admin@reply.yourcompany.com for admin@yourcompany.com). Your replyTo (or fromEmail when you set none) stays first, so replies still reach your mailbox and also arrive in Outbound. The response includes captureReplies: true and the replyDomain that was used. Pass replyDomain to use another of your active reply domains instead of your default; conversations.listReplyDomains() lists them.

Before the first send, an Outbound admin must enable Conversations for your account. To try it without real recipients, send to success@simulator.amazonses.com and create replies with the Sandbox.

While captureReplies is on, headers cannot set Reply-To, References, In-Reply-To or Message-ID.

By default a conversation exists only once a reply arrives. Add createThread: true to open it as soon as the email is sent. Every email that is actually sent gets a conversation this way, so you can list the people who have not replied yet with conversations.listThreads({ hasReplies: false }). Dropped, suppressed and failed emails never open one.

Possible Errors ​

ErrorStatusCause
BadRequestError400replyDomain or createThread given without captureReplies: true (createThread requires captureReplies: true), captureReplies is not a boolean, createThread is not a boolean (createThread must be a boolean), or headers sets Reply-To, References, In-Reply-To or Message-ID
ForbiddenError403Conversations is not enabled for your account
OutboundError422replyDomain is not one of your active reply domains (details.availableReplyDomains lists them), or you have no default reply domain
ServerError503Reply capture is not configured on the platform

List AMP Addresses ​

The AMP addresses assigned to your account. An AMP version (ampBody, or a template with an AMP version) is only sent with one of these as fromEmail. To get one, request it in the dashboard under My Quota. See Get an AMP address.

ts
const { ampAddresses } = await outbound.email.listAmpAddresses();
const gmailReady = ampAddresses.filter((a) => a.registration.gmail.status === 'approved');

Response ​

ts
{
  ampAddresses: [
    {
      email: 'admissions@yourcompany.com',
      registration: {
        gmail: { status: 'approved', reviewSentAt: '2026-10-23T10:00:00.000Z' },
        yahoo: { status: 'submitted', reviewSentAt: '2026-10-23T10:00:00.000Z' },
        mailru: { status: 'not_submitted', reviewSentAt: null }
      }
    }
  ]
}
FieldDescription
emailThe address. Use it as fromEmail on sends with an AMP version
registration.gmail, registration.yahoo, registration.mailruWhere the address stands with each provider. status is not_submitted, submitted (the review email went out), approved (readers there see the AMP version) or rejected. reviewSentAt is when the latest review email went out

Sending never waits for approval. You can send from an AMP address as soon as it is yours, and readers on a provider that has not approved it yet see the HTML version.

Possible Errors ​

ErrorStatusCause
AuthenticationError401Invalid or missing API key

List Email Logs ​

Fetch a page of email logs, newest first, with the delivery details the dashboard's Logs page shows, so you can show them in your own application. Log entries never include the email body. To show an email, pass its messageId to getMessageContent() (see Fetch a Message's Sent Content). For a full walkthrough, see Email Logs in Your Application.

Usage Examples ​

1. Initialize the SDK ​

ts
import { Outbound } from '@masters-union/outbound-sdk';

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

2. Fetch the first 10 logs ​

ts
const { logs, pagination } = await outbound.email.listLogs();

for (const log of logs) {
  console.log(log.createdAt, log.status, log.toEmail, log.subject);
}

console.log(`${pagination.totalRecordsCapped ? '10,000+' : pagination.totalRecords} logs match`);

3. Fetch the next pages ​

ts
const secondPage = await outbound.email.listLogs({ page: 2 });

let page = await outbound.email.listLogs({ pageSize: 50 });
for (const log of page.logs) {
  console.log(log.messageId, log.status);
}

while (page.pagination.hasNextPage) {
  page = await outbound.email.listLogs({ pageSize: 50, page: page.pagination.page + 1 });
  for (const log of page.logs) {
    console.log(log.messageId, log.status);
  }
}

4. Fetch up to 100 per request ​

ts
const { logs } = await outbound.email.listLogs({ pageSize: 100 });

5. Filter the logs ​

ts
// Bounced or failed emails
const problems = await outbound.email.listLogs({
  status: ['bounced', 'failed'],
});

// One recipient, with a date range in India time
const forAlice = await outbound.email.listLogs({
  toEmail: 'alice@example.com',
  startDate: '2026-11-01',
  endDate: '2026-11-05',
  tz: 'Asia/Kolkata',
});

// Every email from one campaign
const campaign = await outbound.email.listLogs({
  campaignId: 'WELCOME-SERIES',
});

6. Handle empty results and errors ​

ts
import {
  AuthenticationError,
  BadRequestError,
  RateLimitError,
} from '@masters-union/outbound-sdk';

try {
  const { logs, dateRange } = await outbound.email.listLogs({ toEmail: 'alice@example.com' });

  if (logs.length === 0) {
    console.log('No matching emails. Searched:', dateRange);
  }
} catch (err) {
  if (err instanceof BadRequestError) {
    console.error('Invalid log search:', err.message, err.details);
  } else if (err instanceof RateLimitError) {
    console.error(`Too many log requests. Retry after ${err.retryAfter}s`);
  } else if (err instanceof AuthenticationError) {
    console.error('Check your API key');
  } else {
    throw err;
  }
}

Parameters ​

All parameters are optional.

NameTypeDefaultDescription
pagenumber1Whole number, 1 or more. Cannot be combined with cursor. Pages reach the first 10,000 logs: (page - 1) * pageSize must be under 10,000
pageSizenumber10Whole number from 1 to 100. Other values are rejected before the request is sent
cursorstringpagination.nextCursor from a previous response. Use it to read past the first 10,000 logs, or for infinite scroll. See Reading Past 10,000 Logs
statusEmailStatus or EmailStatus[]allOne or more of queued, processing, sent, delivered, bounced, complained, opened, clicked, failed, cancelled, dropped
toEmailstringRecipient. A complete address (with @ and a domain) matches exactly, ignoring case. Anything else matches part of the address, for example example.com
fromEmailstringSender address. Same matching rule as toEmail
subjectstringPart of the subject, ignoring case. Up to 200 characters
messageIdstring (UUID)Exact message ID
jobIdstring (UUID)Every message from one send() or bulk() call. For a contact-list send (bulk({ listId })), filter by the returned campaignId instead: its emails are logged under separate jobs, so the returned jobId matches none of them
campaignIdstringExact campaign ID, ignoring case
startDatestring or DateYYYY-MM-DD or ISO 8601 date-time. Logs created on or after this time
endDatestring or DateYYYY-MM-DD (the whole day is included) or ISO 8601 date-time (inclusive)
tzstringUTCIANA time zone used for YYYY-MM-DD dates, for example Asia/Kolkata

Filters ​

  • Filters combine. A log must match every filter you pass. Values inside status combine with OR, so ['bounced', 'failed'] matches either.
  • With no startDate and no endDate, the last 90 days are searched. With only endDate, the 90 days ending at endDate are searched.
  • With messageId, jobId or campaignId and no dates, there is no date limit.
  • The response's dateRange shows the window that was searched. endDate: null means "up to now", and both values null means there is no date limit.
  • Results are ordered newest first, by creation time.
  • Unknown parameters are rejected rather than ignored, so a misspelled filter fails loudly instead of returning everything.

Response ​

ts
{
  logs: [
    {
      messageId: '0193f5a2-7c1e-7b3a-9d42-5e6f7a8b9c0d',
      jobId: '0193f5a2-7b90-7c11-8e2f-1a2b3c4d5e6f',
      campaignId: 'WELCOME-SERIES',
      status: 'delivered',
      errorMessage: null,
      priority: 'normal',
      fromEmail: 'hello@yourdomain.com',
      senderName: 'Your App',
      toEmail: 'alice@example.com',
      ccEmail: null,
      bccEmail: null,
      subject: 'Welcome to Acme',
      providerMessageId: '010f0193f5a27d4e-...-000000',
      createdAt: '2026-11-05T09:30:00.000Z',
      updatedAt: '2026-11-05T09:30:04.000Z',
      sentAt: '2026-11-05T09:30:01.000Z',
      deliveredAt: '2026-11-05T09:30:03.000Z',
      openedAt: null,
      clickedAt: null,
      unsubscribe: null
    }
  ],
  pagination: {
    page: 1,
    pageSize: 10,
    totalRecords: 1234,
    totalRecordsCapped: false,
    totalPages: 124,
    hasNextPage: true,
    hasPreviousPage: false,
    nextCursor: 'eyJ0IjoiMjAyNi0xMS0wNVQwOToz...'
  },
  dateRange: { startDate: '2026-08-07T09:30:00.000Z', endDate: null }
}

Log Fields ​

FieldTypeDescription
messageIdstring (UUID)ID of this message. Pass it to getMessageContent() or getMessageStatus()
jobIdstring (UUID)ID of the send() or bulk() call that created the message
campaignIdstring or nullCampaign ID, stored in uppercase. null if the email has no campaign
statusEmailStatusDelivery result. See the Recipient Status Reference
errorMessagestring or nullWhy the email bounced, failed or was dropped. null otherwise. For dropped emails it reads like Suppressed: bounce
priorityEmailLogPriority or nullcritical, urgent, high, normal, low, deferred or backlog
fromEmailstringSender address
senderNamestring or nullSender display name
toEmailstringRecipient address
ccEmailstring or nullCC recipients, comma-separated. May include display names
bccEmailstring or nullBCC recipients, comma-separated. May include display names
subjectstring or nullSubject line
providerMessageIdstring or nullThe mail provider's ID for the message. null until the email is sent
createdAtstringWhen the log was created, as an ISO 8601 date-time
updatedAtstringWhen the log last changed, as an ISO 8601 date-time
sentAtstring or nullWhen the email was sent. null if it has not been sent
deliveredAtstring or nullWhen the email was delivered. null if it has not been delivered
openedAtstring or nullWhen the recipient first opened the email. null if tracking is off or it was not opened
clickedAtstring or nullWhen the recipient first clicked a link. null if tracking is off or no link was clicked
unsubscribeEmailLogUnsubscribe or nullSet when the recipient unsubscribed from this email: { unsubscribedAt, reason, reasonLabel, comment, source, resubscribed, resubscribedAt }. status still shows the delivery result, so an email can be clicked and unsubscribed at the same time

Pagination ​

FieldTypeDescription
pagenumber or nullCurrent page. null in cursor mode
pageSizenumberLogs per page
totalRecordsnumber or nullMatching logs. Capped at 10,000. null in cursor mode
totalRecordsCappedbooleantrue when more than 10,000 logs match. totalRecords is then 10,000
totalPagesnumber or nullPages you can reach with page. null in cursor mode
hasNextPagebooleantrue when the next page can be requested
hasPreviousPagebooleantrue when there is an earlier page. Always true in cursor mode
nextCursorstring or nullSet whenever more logs exist, even past 10,000. Pass it as cursor to read the next page

Counting stops at 10,000. When more logs match, totalRecordsCapped is true, totalRecords is 10000, and you should show it as "10,000+". totalPages counts the pages you can reach with page. hasNextPage is true only when the next page can be requested. nextCursor is still set when more logs exist past the 10,000 mark, so use a cursor to read them.

Live data and page numbers

Logs are newest first, and new emails keep arriving. With page numbers, an email can move onto the next page while someone is paging, so a log you already saw can show up again. For a stable list, set endDate to the time the list was first loaded and keep it while paging. Cursors do not have this problem.

ts
const loadedAt = new Date().toISOString();

const first = await outbound.email.listLogs({ endDate: loadedAt, pageSize: 50 });
const second = await outbound.email.listLogs({ endDate: loadedAt, pageSize: 50, page: 2 });

Reading Past 10,000 Logs: Cursors ​

Page numbers reach only the first 10,000 logs. To read further, pass pagination.nextCursor as cursor until it comes back null:

ts
import type { EmailLog } from '@masters-union/outbound-sdk';

const all: EmailLog[] = [];
let cursor: string | undefined;

do {
  const page = await outbound.email.listLogs({ pageSize: 100, cursor });
  all.push(...page.logs);
  cursor = page.pagination.nextCursor ?? undefined;
} while (cursor);

A request with cursor returns the cursor response shape. In cursor mode, page, totalRecords and totalPages are null, hasPreviousPage is true, and there is no count. Keep earlier cursors yourself if you want to go back. page and cursor cannot be sent together.

Iterate Over Every Log ​

listAllLogs() takes the same filters as listLogs(), plus pageSize. It has no page or cursor: it fetches 100 logs per request by default, using cursors internally, and yields each log in turn, newest first.

ts
for await (const log of outbound.email.listAllLogs({ startDate: '2026-01-01', status: 'bounced' })) {
  console.log(log.toEmail, log.errorMessage);
}

If a request hits the rate limit, the SDK waits for Retry-After and retries automatically. The 90-day default window applies when you pass no dates, so pass startDate to go further back.

Viewing an Email ​

Logs do not include the email body. To show one, pass the log's messageId to getMessageContent():

ts
const { logs } = await outbound.email.listLogs({ toEmail: 'alice@example.com' });
const content = await outbound.email.getMessageContent(logs[0].messageId);

htmlBody and textBody can be null for older emails, because Outbound keeps email content for a limited time (90 days by default). The log itself stays. See Fetch a Message's Sent Content.

Possible Errors ​

ErrorStatusCause
BadRequestError400Invalid parameter (details.param names it), unknown parameter, page and cursor together, a page past the first 10,000 logs, an invalid cursor, or startDate after endDate. Also thrown by the SDK before sending when page or pageSize is invalid
BadRequestError400details.code is query_timeout: the search took too long. Narrow the date range or use a complete email address. Retrying the same search will not help
AuthenticationError401Missing or invalid API key
ForbiddenError403Account suspended
RateLimitError429More than 120 log requests per minute for your account. The SDK retries automatically using Retry-After before throwing

Get Email Stats ​

Count outcomes for the emails that match your filters: how many were sent, delivered, opened, clicked, bounced and more, with rates. Use it to get totals for a subject or a campaign without paging through logs. Requires SDK 1.3.4 or later.

The method calls GET /v1/email/stats with your X-Api-Key header. You can call the endpoint directly from any HTTP client, as shown in Calling the REST Endpoint.

Usage Examples ​

1. Count a subject over a date range ​

ts
import { Outbound } from '@masters-union/outbound-sdk';

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

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.total, stats.delivered, stats.openRate);

By default the whole subject must match, ignoring case.

2. Count a subject that contains some text ​

ts
const stats = await outbound.email.getStats({
  subject: 'application',
  subjectMatch: 'contains',
});

With no dates, the last 90 days are counted.

3. Count every email in a campaign ​

ts
const stats = await outbound.email.getStats({
  campaignId: 'WELCOME-SERIES',
});

campaignId without dates has no date limit, so this counts the whole campaign.

Parameters ​

All parameters are optional, and they combine. A message must match every filter you pass.

NameTypeDefaultDescription
subjectstringSubject text to count. Up to 200 characters
subjectMatch'exact' or 'contains''exact'exact matches the whole subject, ignoring case. contains matches part of the subject, ignoring case, like the subject filter of listLogs(). Only valid together with subject
campaignIdstringExact campaign ID, ignoring case
fromEmailstringSender address. A complete address (with @ and a domain) matches exactly, ignoring case. Anything else matches as a partial string
startDatestring or DateYYYY-MM-DD or ISO 8601 date-time. Inclusive
endDatestring or DateYYYY-MM-DD includes the whole day. ISO 8601 date-time is inclusive
tzstringUTCIANA time zone used to read date-only values, for example Asia/Kolkata

Unknown parameters are rejected with a 400 error. details.param names the parameter.

Date Window ​

  • With no startDate and no endDate, the last 90 days are counted.
  • campaignId without dates has no date limit. This is the same rule as List Email Logs.
  • The response's dateRange shows the window the server applied. endDate: null means "up to now".

Response ​

ts
{
  total: 6893,
  sent: 6893,
  delivered: 5811,
  opened: 1730,
  clicked: 320,
  bounced: 129,
  complained: 0,
  failed: 0,
  dropped: 0,
  unsubscribed: 20,
  deliveryRate: 84.3,
  openRate: 29.77,
  clickRate: 5.51,
  bounceRate: 1.87,
  subjectMatch: 'exact',
  dateRange: { startDate: '2026-08-31T18:30:00.000Z', endDate: '2026-11-30T18:29:59.999Z' }
}

Count Fields ​

FieldTypeDescription
totalnumberEvery email that matches the filters
sentnumberEmails handed to the email provider
deliverednumberEmails that ever reached delivery, meaning their deliveredAt is set. An email counts even if its current status is different
openednumberEmails that were ever opened, meaning their openedAt is set. Includes emails that were also clicked
clickednumberEmails that were ever clicked, meaning their clickedAt is set
bouncednumberEmails whose final status is bounced
complainednumberEmails whose final status is complained
failednumberEmails whose final status is failed
droppednumberEmails whose final status is dropped. These were never sent, because the address was suppressed or invalid
unsubscribednumberEmails the recipient unsubscribed from. Counted even if they later resubscribed

The funnel is cumulative. opened includes clicked emails, and delivered includes opened ones.

Rates ​

FieldTypeFormula
deliveryRatenumberdelivered / sent
openRatenumberopened / delivered
clickRatenumberclicked / delivered
bounceRatenumberbounced / sent

Rates are percentages with 2 decimals. A rate is 0 when its denominator is 0. Because the rates are included, you don't need to compute your own funnel from the counts.

subjectMatch shows the match mode the server applied, or null when you did not pass a subject.

Freshness and Speed ​

  • Results may be up to 60 seconds old. Identical requests are cached briefly.
  • exact, the default, is the fastest form. A short contains phrase can match many different subjects and hundreds of thousands of emails. That can take several seconds or end in a query_timeout error, so narrow the date range or add campaignId.

Calling the REST Endpoint ​

The REST endpoint works with any HTTP client. Send your API key in the X-Api-Key header:

ts
const url = new URL('https://outbound-api.unionstack.in/v1/email/stats');
url.searchParams.set('subject', 'Your application is complete');

const res = await fetch(url, {
  headers: { 'X-Api-Key': process.env.OUTBOUND_API_KEY! },
});
const stats = await res.json();

Possible Errors ​

ErrorStatusCause
BadRequestError400Invalid or unknown parameter (details.param names it), or subjectMatch without subject
BadRequestError400details.code is query_timeout: the count took too long. Narrow the date range, use subjectMatch=exact, or filter by campaignId. The SDK does not retry this error
AuthenticationError401Missing or invalid API key
RateLimitError429More than 60 stats requests per minute for your account, shared by all your API keys. The SDK retries automatically using Retry-After before throwing

Check Job Status ​

Track the delivery status of every recipient in a job.

ts
const status = await outbound.email.status('550e8400-e29b-41d4-a716-446655440000');

Response ​

ts
{
  job: {
    id: '550e8400-e29b-41d4-a716-446655440000',
    tenant_id: 'uuid',
    total_recipients: 500,
    status: 'completed',       // 'queued' | 'processing' | 'completed' | 'failed'
    priority: 'normal',
    created_at: '2026-03-08T10:00:00.000Z',
    updated_at: '2026-03-08T10:01:00.000Z'
  },
  recipients: [
    {
      message_id: '660e8400-e29b-41d4-a716-446655440001',
      recipient_email: 'alice@example.com',
      status: 'delivered',
      ses_message_id: 'aws-ses-message-id',
      error_message: null,
      created_at: '2026-03-08T10:00:00.000Z'
    },
    {
      message_id: '660e8400-e29b-41d4-a716-446655440002',
      recipient_email: 'bad-address@example.com',
      status: 'bounced',
      ses_message_id: 'aws-ses-message-id',
      error_message: null,
      created_at: '2026-03-08T10:00:00.000Z'
    },
    {
      message_id: '660e8400-e29b-41d4-a716-446655440003',
      recipient_email: 'invalid@nonexistent.tld',
      status: 'failed',
      ses_message_id: null,
      error_message: 'Email address not verified',
      created_at: '2026-03-08T10:00:00.000Z'
    }
  ]
}

Check a Single Message's Status ​

Look up the current status of one message by its messageId — the ID returned from send() / bulk() and included in webhook payloads. This is the way to reconcile a message whose webhook was missed.

Accepts only a message ID — not a job ID or SES message ID. The message must belong to the tenant your API key is scoped to, otherwise a NotFoundError is thrown.

ts
const result = await outbound.email.getMessageStatus('660e8400-e29b-41d4-a716-446655440001');

Response ​

ts
{
  recipient: {
    message_id: '660e8400-e29b-41d4-a716-446655440001',
    job_id: '550e8400-e29b-41d4-a716-446655440000',
    recipient_email: 'alice@example.com',
    from_email: 'hello@yourdomain.com',
    sender_name: 'Your App',
    subject: 'Welcome!',
    status: 'delivered',
    ses_message_id: 'aws-ses-message-id',
    error_message: null,
    created_at: '2026-03-08T10:00:00.000Z',
    updated_at: '2026-03-08T10:01:00.000Z'
  }
}

The status reflects the latest event recorded for the message by the SES event pipeline (configuration-set event destinations → stored events), so the stored status already reflects the most recent delivery/open/click/bounce SES has reported.


Recipient Status Reference ​

StatusDescriptionFinal?
queuedWaiting in the queueNo
processingBeing sent to AWS SESNo
sentSES accepted the emailNo
deliveredDelivered to recipient's mailboxYes
bouncedHard or soft bounceYes
complainedRecipient reported as spamYes
openedRecipient opened the emailNo (can become clicked)
clickedRecipient clicked a linkYes
failedFailed to send to SESYes
cancelledCancelled before sending via email.cancel()Yes
droppedRecipient was on the suppression list at submit time — never attempted. error_message is Suppressed: <bounce|complaint|manual|unsubscribe>Yes

Status Updates

Statuses update asynchronously as AWS SES sends delivery notifications back to the platform. sent → delivered can take a few seconds to a few minutes. opened and clicked events depend on tracking being enabled and may arrive hours later.

Polling Example ​

ts
async function waitForDelivery(jobId: string, maxAttempts = 10) {
  for (let i = 0; i < maxAttempts; i++) {
    const { recipients } = await outbound.email.status(jobId);

    const allDone = recipients.every(r =>
      ['delivered', 'bounced', 'complained', 'failed', 'cancelled', 'dropped'].includes(r.status)
    );

    if (allDone) {
      const delivered = recipients.filter(r => r.status === 'delivered').length;
      console.log(`${delivered}/${recipients.length} delivered`);
      return recipients;
    }

    await new Promise(resolve => setTimeout(resolve, 2000));
  }

  throw new Error('Timed out waiting for delivery');
}

Possible Errors ​

ErrorStatusCause
NotFoundError404Job ID doesn't exist or belongs to a different tenant
AuthenticationError401Invalid API key

Fetch a Message's Sent Content ​

Fetch the content that was sent for one message by its messageId — the subject, envelope and htmlBody / textBody. This is the same content the dashboard renders in its Preview, so you can reconstruct or re-display a sent email in your own UI.

htmlBody is returned as sent, including the unsubscribe footer the platform appends. Attachments are not inlined. Accepts only a message ID — not a job ID or SES message ID — and the message must belong to the tenant your API key is scoped to, otherwise a NotFoundError is thrown.

ts
const content = await outbound.email.getMessageContent('660e8400-e29b-41d4-a716-446655440001');

Response ​

ts
{
  messageId: '660e8400-e29b-41d4-a716-446655440001',
  jobId: '550e8400-e29b-41d4-a716-446655440000',
  status: 'delivered',
  subject: 'Welcome to Acme',
  fromEmail: 'hello@yourdomain.com',
  senderName: 'Your App',
  replyTo: 'support@yourdomain.com',
  toEmail: 'alice@example.com',
  ccEmail: null,
  bccEmail: null,
  htmlBody: '<html>...as sent, incl. unsubscribe footer...</html>',
  textBody: 'Plain-text alternative, or null',
  ampBody: 'AMP version as stored (with its unsubscribe footer), or null',
  createdAt: '2026-03-08T10:00:00.000Z',
  sentAt: '2026-03-08T10:00:02.000Z'
}

Rendering the Preview ​

ts
const { htmlBody, subject } = await outbound.email.getMessageContent(messageId);

// e.g. render inside a sandboxed iframe in your dashboard
iframe.srcdoc = htmlBody ?? '';
document.querySelector('#subject').textContent = subject ?? '(no subject)';

Possible Errors ​

ErrorStatusCause
BadRequestError400messageId is not a valid UUID
NotFoundError404No message with this Message ID for this tenant
AuthenticationError401Invalid API key

Cancel a Campaign or Job ​

Stop queued emails before they are sent. Use this when emails were triggered for the wrong audience or need to be aborted.

ts
// Cancel all jobs belonging to a campaign
await outbound.email.cancel({ campaignId: 'launch-2026-q2' });

// Cancel a single specific job
await outbound.email.cancel({ jobId: '550e8400-e29b-41d4-a716-446655440000' });

How cancellation works ​

Only recipients still in queued or processing state are cancelled. Recipients already sent or delivered cannot be recalled — cancellation is not an unsend.

The platform does two things on cancel:

  1. Marks recipients as cancelled in the database — the worker checks this and skips them
  2. Removes the job from the queue if it hasn't started yet (removedFromQueue in the response tells you how many were removed this way)

Using campaignId for bulk cancellation ​

Pass campaignId when sending to group multiple API calls under one campaign. A single cancel() call then stops all of them:

ts
// Send in 3 batches, all tagged to the same campaign
for (let i = 0; i < batches.length; i++) {
  await outbound.email.bulk({
    fromEmail: 'campaigns@company.com',
    emailSubject: 'Spring Sale',
    campaignId: 'spring-sale-2026',   // same ID across all batches
    emails: batches[i],
  });
}

// Oops — wrong audience. Cancel everything.
const result = await outbound.email.cancel({ campaignId: 'spring-sale-2026' });
console.log(`Cancelled ${result.cancelledRecipients} recipients across ${result.cancelledJobs} jobs`);

This also works with template sends:

ts
await outbound.templates.bulkSend({
  templateId: 'promo-template',
  fromEmail: 'campaigns@company.com',
  campaignId: 'spring-sale-2026',
  recipients: [ ... ],
});

await outbound.email.cancel({ campaignId: 'spring-sale-2026' });

Parameters ​

FieldTypeRequiredDescription
campaignIdstringOne ofCancel all jobs tagged with this campaign ID
jobIdstringOne ofCancel a single specific job

Response ​

ts
{
  message: 'Cancelled successfully',
  cancelledJobs: 3,           // number of EmailJob records cancelled
  cancelledRecipients: 1420,  // individual recipients set to 'cancelled'
  removedFromQueue: 2         // jobs removed from BullMQ before processing started
}

Possible Errors ​

ErrorStatusCause
BadRequestError400Neither campaignId nor jobId provided
NotFoundError404No jobs found for this tenant matching the criteria
ConflictError409All matching jobs are already completed, failed, or cancelled

Released under the MIT License.