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.
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
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
| Field | Type | Required | Description |
|---|---|---|---|
toEmail | string | Yes | Recipient email address |
fromEmail | string | Yes | Sender email — must be a verified domain assigned to your tenant |
emailSubject | string | Yes | Email subject line |
htmlBody | string | Yes | HTML email body |
textBody | string | No | Plain text alternative (recommended for deliverability) |
ampBody | string | No | AMP 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 |
senderName | string | No | Display name shown to recipient |
replyTo | string | No | Reply-to email address |
ccEmail | string | No | CC recipient |
bccEmail | string | No | BCC recipient |
priority | string | No | 'critical', 'urgent', 'high', 'normal' (default), 'low', 'deferred', or 'backlog'. Unrecognized values are treated as 'normal'. |
idempotencyKey | string | No | Unique key to prevent duplicate sends — expires after 24 hours (see below) |
campaignId | string | No | Tag this email as part of a campaign — enables bulk cancellation via email.cancel() |
metadata | object | No | Custom key-value pairs stored with the email |
headers | object | No | Custom email headers |
tracking | object | No | Open and click tracking configuration |
attachments | Attachment[] | No | File attachments (max 25MB each, 25MB total) |
captureReplies | boolean | No | Collect replies to this email as a conversation. Default false. See Capturing Replies |
replyDomain | string | No | Which of your reply domains to use instead of your default. Requires captureReplies: true |
createThread | boolean | No | Open the conversation as soon as the email is sent, so emails nobody has replied to are listed too. Default false. Requires captureReplies: true |
Response
{
message: 'Email queued successfully',
jobId: '550e8400-e29b-41d4-a716-446655440000',
messageId: '660e8400-e29b-41d4-a716-446655440001'
}| Field | Description |
|---|---|
jobId | Unique job ID — use this to check delivery status |
messageId | Unique message ID for this specific recipient |
captureReplies | true when replies to this email are captured. Absent otherwise |
replyDomain | The reply domain used. Present only with captureReplies |
createThread | true or false: whether the conversation is opened at send. Present only with captureReplies |
Possible Errors
| Error | Status | Cause |
|---|---|---|
BadRequestError | 400 | Missing required fields, invalid email format |
AuthenticationError | 401 | Invalid or missing API key |
ForbiddenError | 403 | Domain not verified, tenant suspended |
ConflictError | 409 | Idempotency key is currently being processed by another request |
OutboundError | 422 | ampBody is set and fromEmail is not one of your AMP addresses (details.availableAmpAddresses lists them). See List AMP Addresses |
RateLimitError | 429 | Per-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.
// 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 === trueHow 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) withduplicate: 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:
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):
// 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:
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: trueWhy 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
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.
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
| Field | Type | Required | Description |
|---|---|---|---|
fromEmail | string | Yes | Sender email (verified domain) |
emailSubject | string | Yes | Default subject for all recipients |
emails | BulkEmailRecipient[] | Yes | Array of recipients (max 500) |
senderName | string | No | Display name |
replyTo | string | No | Reply-to address |
ampBody | string | No | Shared 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 |
priority | string | No | '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. |
idempotencyKey | string | No | Prevents duplicate bulk sends — expires after 24 hours |
campaignId | string | No | Tag this batch as part of a campaign — enables bulk cancellation via email.cancel() |
captureReplies | boolean | No | Collect replies to every email in the batch as conversations. Default false. See Capturing Replies |
replyDomain | string | No | Which of your reply domains to use instead of your default. Requires captureReplies: true |
createThread | boolean | No | Open 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
| Field | Type | Required | Description |
|---|---|---|---|
toEmail | string | Yes | Recipient email address |
htmlBody | string | Yes | HTML body for this specific recipient |
subject | string | No | Override the default emailSubject for this recipient |
textBody | string | No | Plain text alternative |
ampBody | string | No | AMP version for this recipient. A recipient with its own htmlBody never inherits the shared ampBody |
ccEmail | string | No | CC recipient |
bccEmail | string | No | BCC recipient |
metadata | object | No | Custom metadata for this recipient |
Response
{
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:
- Deduplication — If you include the same
toEmailtwice, only the first occurrence is kept - Suppression filtering — Emails on your suppression list (bounces, complaints, manual suppressions, unsubscribes) are silently removed from the send but persisted as
droppedrecipient rows on the job, so you can audit them viaemail.status(jobId) - 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
| Error | Status | Cause |
|---|---|---|
BadRequestError | 400 | Empty emails array, exceeds 500 limit, missing required fields |
ForbiddenError | 403 | Domain not verified, tenant suspended |
ConflictError | 409 | Idempotency key is currently being processed by another request |
OutboundError | 422 | An ampBody (shared or on any recipient) is set and fromEmail is not one of your AMP addresses (details.availableAmpAddresses lists them) |
RateLimitError | 429 | Exceeded 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.
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
| Error | Status | Cause |
|---|---|---|
BadRequestError | 400 | replyDomain 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 |
ForbiddenError | 403 | Conversations is not enabled for your account |
OutboundError | 422 | replyDomain is not one of your active reply domains (details.availableReplyDomains lists them), or you have no default reply domain |
ServerError | 503 | Reply 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.
const { ampAddresses } = await outbound.email.listAmpAddresses();
const gmailReady = ampAddresses.filter((a) => a.registration.gmail.status === 'approved');Response
{
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 }
}
}
]
}| Field | Description |
|---|---|
email | The address. Use it as fromEmail on sends with an AMP version |
registration.gmail, registration.yahoo, registration.mailru | Where 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
| Error | Status | Cause |
|---|---|---|
AuthenticationError | 401 | Invalid 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
import { Outbound } from '@masters-union/outbound-sdk';
const outbound = new Outbound({ apiKey: process.env.OUTBOUND_API_KEY });2. Fetch the first 10 logs
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
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
const { logs } = await outbound.email.listLogs({ pageSize: 100 });5. Filter the logs
// 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
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.
| Name | Type | Default | Description |
|---|---|---|---|
page | number | 1 | Whole number, 1 or more. Cannot be combined with cursor. Pages reach the first 10,000 logs: (page - 1) * pageSize must be under 10,000 |
pageSize | number | 10 | Whole number from 1 to 100. Other values are rejected before the request is sent |
cursor | string | pagination.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 | |
status | EmailStatus or EmailStatus[] | all | One or more of queued, processing, sent, delivered, bounced, complained, opened, clicked, failed, cancelled, dropped |
toEmail | string | Recipient. A complete address (with @ and a domain) matches exactly, ignoring case. Anything else matches part of the address, for example example.com | |
fromEmail | string | Sender address. Same matching rule as toEmail | |
subject | string | Part of the subject, ignoring case. Up to 200 characters | |
messageId | string (UUID) | Exact message ID | |
jobId | string (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 | |
campaignId | string | Exact campaign ID, ignoring case | |
startDate | string or Date | YYYY-MM-DD or ISO 8601 date-time. Logs created on or after this time | |
endDate | string or Date | YYYY-MM-DD (the whole day is included) or ISO 8601 date-time (inclusive) | |
tz | string | UTC | IANA 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
statuscombine with OR, so['bounced', 'failed']matches either. - With no
startDateand noendDate, the last 90 days are searched. With onlyendDate, the 90 days ending atendDateare searched. - With
messageId,jobIdorcampaignIdand no dates, there is no date limit. - The response's
dateRangeshows the window that was searched.endDate: nullmeans "up to now", and both valuesnullmeans 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
{
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
| Field | Type | Description |
|---|---|---|
messageId | string (UUID) | ID of this message. Pass it to getMessageContent() or getMessageStatus() |
jobId | string (UUID) | ID of the send() or bulk() call that created the message |
campaignId | string or null | Campaign ID, stored in uppercase. null if the email has no campaign |
status | EmailStatus | Delivery result. See the Recipient Status Reference |
errorMessage | string or null | Why the email bounced, failed or was dropped. null otherwise. For dropped emails it reads like Suppressed: bounce |
priority | EmailLogPriority or null | critical, urgent, high, normal, low, deferred or backlog |
fromEmail | string | Sender address |
senderName | string or null | Sender display name |
toEmail | string | Recipient address |
ccEmail | string or null | CC recipients, comma-separated. May include display names |
bccEmail | string or null | BCC recipients, comma-separated. May include display names |
subject | string or null | Subject line |
providerMessageId | string or null | The mail provider's ID for the message. null until the email is sent |
createdAt | string | When the log was created, as an ISO 8601 date-time |
updatedAt | string | When the log last changed, as an ISO 8601 date-time |
sentAt | string or null | When the email was sent. null if it has not been sent |
deliveredAt | string or null | When the email was delivered. null if it has not been delivered |
openedAt | string or null | When the recipient first opened the email. null if tracking is off or it was not opened |
clickedAt | string or null | When the recipient first clicked a link. null if tracking is off or no link was clicked |
unsubscribe | EmailLogUnsubscribe or null | Set 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
| Field | Type | Description |
|---|---|---|
page | number or null | Current page. null in cursor mode |
pageSize | number | Logs per page |
totalRecords | number or null | Matching logs. Capped at 10,000. null in cursor mode |
totalRecordsCapped | boolean | true when more than 10,000 logs match. totalRecords is then 10,000 |
totalPages | number or null | Pages you can reach with page. null in cursor mode |
hasNextPage | boolean | true when the next page can be requested |
hasPreviousPage | boolean | true when there is an earlier page. Always true in cursor mode |
nextCursor | string or null | Set 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.
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:
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.
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():
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
| Error | Status | Cause |
|---|---|---|
BadRequestError | 400 | Invalid 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 |
BadRequestError | 400 | details.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 |
AuthenticationError | 401 | Missing or invalid API key |
ForbiddenError | 403 | Account suspended |
RateLimitError | 429 | More 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
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
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
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.
| Name | Type | Default | Description |
|---|---|---|---|
subject | string | Subject 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 |
campaignId | string | Exact campaign ID, ignoring case | |
fromEmail | string | Sender address. A complete address (with @ and a domain) matches exactly, ignoring case. Anything else matches as a partial string | |
startDate | string or Date | YYYY-MM-DD or ISO 8601 date-time. Inclusive | |
endDate | string or Date | YYYY-MM-DD includes the whole day. ISO 8601 date-time is inclusive | |
tz | string | UTC | IANA 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
startDateand noendDate, the last 90 days are counted. campaignIdwithout dates has no date limit. This is the same rule as List Email Logs.- The response's
dateRangeshows the window the server applied.endDate: nullmeans "up to now".
Response
{
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
| Field | Type | Description |
|---|---|---|
total | number | Every email that matches the filters |
sent | number | Emails handed to the email provider |
delivered | number | Emails that ever reached delivery, meaning their deliveredAt is set. An email counts even if its current status is different |
opened | number | Emails that were ever opened, meaning their openedAt is set. Includes emails that were also clicked |
clicked | number | Emails that were ever clicked, meaning their clickedAt is set |
bounced | number | Emails whose final status is bounced |
complained | number | Emails whose final status is complained |
failed | number | Emails whose final status is failed |
dropped | number | Emails whose final status is dropped. These were never sent, because the address was suppressed or invalid |
unsubscribed | number | Emails the recipient unsubscribed from. Counted even if they later resubscribed |
The funnel is cumulative. opened includes clicked emails, and delivered includes opened ones.
Rates
| Field | Type | Formula |
|---|---|---|
deliveryRate | number | delivered / sent |
openRate | number | opened / delivered |
clickRate | number | clicked / delivered |
bounceRate | number | bounced / 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 shortcontainsphrase can match many different subjects and hundreds of thousands of emails. That can take several seconds or end in aquery_timeouterror, so narrow the date range or addcampaignId.
Calling the REST Endpoint
The REST endpoint works with any HTTP client. Send your API key in the X-Api-Key header:
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
| Error | Status | Cause |
|---|---|---|
BadRequestError | 400 | Invalid or unknown parameter (details.param names it), or subjectMatch without subject |
BadRequestError | 400 | details.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 |
AuthenticationError | 401 | Missing or invalid API key |
RateLimitError | 429 | More 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.
const status = await outbound.email.status('550e8400-e29b-41d4-a716-446655440000');Response
{
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.
const result = await outbound.email.getMessageStatus('660e8400-e29b-41d4-a716-446655440001');Response
{
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
statusalready reflects the most recent delivery/open/click/bounce SES has reported.
Recipient Status Reference
| Status | Description | Final? |
|---|---|---|
queued | Waiting in the queue | No |
processing | Being sent to AWS SES | No |
sent | SES accepted the email | No |
delivered | Delivered to recipient's mailbox | Yes |
bounced | Hard or soft bounce | Yes |
complained | Recipient reported as spam | Yes |
opened | Recipient opened the email | No (can become clicked) |
clicked | Recipient clicked a link | Yes |
failed | Failed to send to SES | Yes |
cancelled | Cancelled before sending via email.cancel() | Yes |
dropped | Recipient 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
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
| Error | Status | Cause |
|---|---|---|
NotFoundError | 404 | Job ID doesn't exist or belongs to a different tenant |
AuthenticationError | 401 | Invalid 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.
const content = await outbound.email.getMessageContent('660e8400-e29b-41d4-a716-446655440001');Response
{
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
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
| Error | Status | Cause |
|---|---|---|
BadRequestError | 400 | messageId is not a valid UUID |
NotFoundError | 404 | No message with this Message ID for this tenant |
AuthenticationError | 401 | Invalid 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.
// 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:
- Marks recipients as
cancelledin the database — the worker checks this and skips them - Removes the job from the queue if it hasn't started yet (
removedFromQueuein 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:
// 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:
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
| Field | Type | Required | Description |
|---|---|---|---|
campaignId | string | One of | Cancel all jobs tagged with this campaign ID |
jobId | string | One of | Cancel a single specific job |
Response
{
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
| Error | Status | Cause |
|---|---|---|
BadRequestError | 400 | Neither campaignId nor jobId provided |
NotFoundError | 404 | No jobs found for this tenant matching the criteria |
ConflictError | 409 | All matching jobs are already completed, failed, or cancelled |