Skip to content

SDKs and toolsTypeScript SDK

TypeScript SDK

The official shipmail package covers the whole API with typed requests and responses. It runs on Node.js 18+, Bun, Deno and edge runtimes.

Last updated

Installation

npm install shipmail

Member roles and mailbox access

const members = await shipmail.members.list({ limit: 25 });
const member = await shipmail.members.get("mem_alice");
console.log(member.role, member.mailbox_access.scope, member.mailbox_access.mailbox_ids);

// Needs members:write
const invitation = await shipmail.members.invite(
  { email: "sam@acme.com", role: "member", mailbox_ids: ["mbx_123"] },
  { idempotencyKey: "invite-sam" },
);
const pending = await shipmail.members.listInvitations();
await shipmail.members.cancelInvitation(invitation.id);
await shipmail.members.grantMailboxAccess("mem_alice", "mbx_123");
await shipmail.members.revokeMailboxAccess("mem_alice", "mbx_123");

Roles are owner, admin, or member. mailbox_access contains a scope of all or selected and a mailbox_ids array, empty for all.

With selected access, you only see the mailbox IDs your key can reach, so the list may be incomplete. An empty selected list may mean no grants or no visible grants. A key with only members:read has no mail reach and returns no selected mailbox IDs.

Inviting people and sharing mailboxes need members:write, which no preset includes (an All access key does). The invitee receives an email and creates their own account; you never receive their credentials. See the Members API for who may grant which mailboxes.

Quick start

import Shipmail from "shipmail";

const shipmail = new Shipmail(process.env.SHIPMAIL_API_KEY);

// Send an email
const message = await shipmail.messages.send({
  from: "hello@yourdomain.com",
  to: ["recipient@example.com"],
  subject: "Hello from Shipmail",
  text: "It works.",
  client_reference: "crm-123",
  metadata: { campaign: "onboarding" },
  source_rfc_message_id: "<crm-123@yourdomain.com>",
});

const sameMessage = await shipmail.messages.list({ client_reference: "crm-123" });
await shipmail.mailboxes.suspend("mbx_123");
await shipmail.mailboxes.resume("mbx_123");
const forwarding = await shipmail.mailboxes.createForwarding("mbx_123", {
  destination: "owner@example.net",
});
const forwardingList = await shipmail.mailboxes.listForwarding("mbx_123");
const appPassword = await shipmail.mailboxes.createAppPassword("mbx_123", {
  name: "Desktop mail",
  expires_at: "2026-10-01T00:00:00Z",
});
const appPasswords = await shipmail.mailboxes.listAppPasswords("mbx_123");
await shipmail.mailboxes.revokeAppPassword("mbx_123", appPassword.id);
const smtpCredential = await shipmail.smtpCredentials.create({
  from: "notifications@notify.example.com",
  name: "Supabase Auth",
});
await shipmail.smtpCredentials.list({ from: "notifications@notify.example.com" });
await shipmail.smtpCredentials.revoke(smtpCredential.id);
const txDomain = await shipmail.transactionalDomains.create({
  root_domain: "example.com",
  subdomain: "notify",
});
// Publish txDomain.dns_records, then check until status is "verified"
await shipmail.transactionalDomains.verify(txDomain.id);
const sender = await shipmail.transactionalSenders.create({
  domain_id: txDomain.id,
  mailbox_id: "mbx_123",
  local_part: "notifications",
  display_name: "Acme",
});
await shipmail.transactionalSenders.update(sender.id, { refuse_disposable: true });
const rules = await shipmail.mailboxes.getRules("mbx_123");
await shipmail.mailboxes.updateRules("mbx_123", {
  rules: rules.rules,
});
const mailboxExport = await shipmail.mailboxes.createExport("mbx_123");
const exportStatus = await shipmail.mailboxes.getExport("mbx_123", mailboxExport.id);
console.log(message.id, sameMessage.data[0]?.id, forwarding.status, forwardingList.data.length);

Direct newsletter media uploads

Uploads take three steps. Prepare the upload with the file's exact SHA-256 digest, PUT the bytes straight to storage, then call the completion URL, which needs no API key. For a video, the response also has a second PUT for the JPEG poster.

const prepared = await shipmail.newsletters.assets.prepareUpload({
  filename,
  content_type: contentType,
  size: bytes.byteLength,
  sha256,
});

await fetch(prepared.upload_url, {
  method: prepared.upload_method,
  headers: prepared.upload_headers,
  body: bytes,
});

// For prepared.kind === "video", upload a JPEG poster with the thumbnail_* fields first.
const asset = await fetch(prepared.complete_url, {
  method: prepared.complete_method,
}).then((response) => response.json());

Sandbox

With an sm_test_... key you can fake outbound results and call mailboxes.injectSandboxInbound(). Nothing sent in the sandbox reaches a real recipient. See the sandbox guide.

Configuration

Pass the API key as a string, or pass an object to set the other options:

const shipmail = new Shipmail({
  apiKey: process.env.SHIPMAIL_API_KEY,
  baseUrl: "https://shipmail.to/api/v1",  // default
  maxRetries: 2,                           // default
  timeout: 30_000,                         // ms, default
  defaultHeaders: { "X-Custom": "value" },
});
OptionDefaultDescription
apiKeyrequiredYour sm_live_... key.
baseUrlhttps://shipmail.to/api/v1API base URL.
maxRetries2Retry count for eligible requests; 0 disables retries.
timeout30000Request timeout in ms.
defaultHeaders{}Headers sent with every request.
fetchglobalThis.fetchYour own fetch, for tests or a proxy.

Resources

Each API resource is a property on the client:

PropertyMethods
shipmail.organizationaccess: plan, access, trial and mailbox capacity. See GET /v1/organization/access.
shipmail.domainscreate, list, get, getDnsRecords, getHealth, update, delete, verify, search, register
shipmail.mailboxescreate, list, get, update, delete, listFolders, createFolder, updateFolder, deleteFolder, listIdentities, listInboxMessages, getInboxMessage, listInboxThreads, getInboxThread, updateInboxThreadAttention, createInboxDraft, createInboxReplyDraft, listInboxReplyDrafts, getInboxReplyDraft, updateInboxReplyDraft, deleteInboxReplyDraft, sendInboxReplyDraft, replyToInboxMessage, replyToInboxThread, updateInboxMessage, moveInboxMessage, deleteInboxMessage, downloadInboxAttachment, resetPassword, getRules, updateRules, listForwarding, createForwarding, deleteForwarding, updateAutoReply, createExport, getExport, createImport, listImports, getImport, cancelImport, resumeImport, restoreImport, undoImport, createImportUpload
shipmail.replyScanscreate, get, listResults
shipmail.messagessend (with a template or your own content), list, get, reply, respondToInvitation
shipmail.templatescreate, list, get, update, delete, publish, render, listVersions, getVersion, restoreVersion
shipmail.memberslist, listAutoPaginating, get, listInvitations, invite, cancelInvitation, grantMailboxAccess, revokeMailboxAccess
shipmail.threadslist, get, reply
shipmail.webhookscreate, list, get, update, delete, rotateSecret, test, listDeliveries
shipmail.eventQueuescreate, list, listAutoPaginating, get, delete, listEvents, ack
shipmail.smtpCredentialslist (filter by from), create (returns the password once), revoke
shipmail.transactionalDomainslist, create, get, verify, delete
shipmail.transactionalSenderslist (filter by domain_id), create, get, update
shipmail.suppressionscreate, list (filter by scope), remove
shipmail.customerslist, get, create, update, remove, upsertByExternalId, listServiceLevels, listFields
shipmail.audiencescreate, list, get, update, delete
shipmail.automationscreate, list, get, update, run
shipmail.audiences.subscribersadd, addBatch, list, get, getByEmail, update, unsubscribe, resubscribe, resendConfirmation, remove
shipmail.audiences.feedsget, update, rotate, revoke
shipmail.audiences.segmentslist, create, get, update, delete
shipmail.newsletterscreate, createFromChangelog, list, get, update, preview, preflight, sendTest, schedule, cancel, resume
shipmail.newsletters.domainslist
shipmail.newsletters.assetslist, upload, registerFromUrl
shipmail.calendar.eventscreate, list, get, update, delete
shipmail.calendaravailability
shipmail.bookingPagescreate, list, get, update, delete
shipmail.bookingLinkscreate, list, get, update, revoke
shipmail.statusget

Paginated list methods also have a listAutoPaginating variant that returns an async iterator over every page.

Calendar invitation language

const created = await shipmail.calendar.events.create({
  mailbox: "hello@yourdomain.com",
  operation_key: "calendar-create-01",
  send_invitations: true,
  title: "Intro call",
  start: "2026-08-07T08:30:00",
  timezone: "Europe/Paris",
  duration: "PT1H",
  invitation_language: "fr",
  attendees: [{ email: "guest@example.com" }],
});

Use en, fr, or es. Later update and cancellation messages for that event use the same language.

Reuse operation_key only to retry the exact same payload. Mutation responses expose per-recipient invitation_outcomesand the compatibility invitation_failures list. Read revision from an event and pass it as expected_revision on updates; send_guest_updates controls scheduling messages.

Answer a calendar invitation

const answer = await shipmail.messages.respondToInvitation("msg_123", {
  response: "accepted", // or "tentative", "declined"
});
answer.replied; // true when the organizer got the answer by email
answer.calendar_event_id;

The message.received webhook carries the invitation as data.invitation, typed WebhookInvitation | null. Needs calendar:write.

Email templates

const template = await shipmail.templates.create({
  name: "Welcome",
  subject: "Welcome, {{name}}",
  html: "<p>Hi {{name}}, you are on the {{plan}} plan.</p>",
  fallbacks: { plan: "Free" }, // a key without a fallback is required at send time
  publish: true, // also publish the draft as version 1
});

const preview = await shipmail.templates.render(template.id, { variables: { name: "Ada" } });

await shipmail.messages.send({
  from: "hello@example.com",
  to: ["ada@example.com"],
  template: { id: template.id, variables: { name: "Ada" } }, // no subject, html or text
});

await shipmail.templates.update(template.id, { subject: "Welcome aboard, {{name}}" }); // draft only
await shipmail.templates.publish(template.id); // version 2
await shipmail.templates.restoreVersion(template.id, 1); // copies version 1 into the draft

A send naming an unknown template throws NotFoundError. A template that was never published, a required variable left out, or a variable the template does not use throws ValidationError, whose details[].code is template_not_published, missing_variable or unknown_variable. See the Templates API.

Automations

const definition = {
  trigger: { type: "scheduled" as const, cron: "0 8 * * *", time_zone: "Europe/Lisbon" },
  conditions: [],
  actions: [{ type: "generate_mail_report" as const, metric: "received" as const, lookback_minutes: 1440 }],
  mode: "draft" as const,
  scope: { mailbox_ids: ["mbx_123"], calendar_addresses: [] },
};

const automation = await shipmail.automations.create({
  name: "Daily brief",
  definition,
});

await shipmail.automations.update(automation.id, { status: "paused" });

Create takes a typed definition and turns it on in one step. Only call run on a definition with a manual trigger. See the Automations API.

Audience feed settings

const feed = await shipmail.audiences.feeds.update("aud_123", {
  canonical_url: "https://example.com/feed.xml",
  entry_limit: 25,
});

console.log(feed.canonical_url, feed.entry_limit);

// Clear the canonical URL and return to the default 50-entry feed.
await shipmail.audiences.feeds.update("aud_123", {
  canonical_url: null,
  entry_limit: null,
});

The entry limit is a whole number from 10 to 100. Leave a property out to keep its current value. A null in the response means null is what's stored, not that a default was filled in.

Booking page conferencing

const page = await shipmail.bookingPages.create({
  name: "Intro call",
  mailbox: "hello@yourdomain.com",
  slug: "intro",
  duration_minutes: 30,
  availability_days: [1, 2, 3, 4, 5],
  window_start_minutes: 540,
  window_end_minutes: 1020,
  timezone: "America/New_York",
  conferencing_provider: "zoom",
});

await shipmail.bookingPages.update(page.id, {
  conferencing_provider: null,
});

The provider is off until you set it, and it must already be connected to the booking page's mailbox. Use null to stop creating meeting links. See conferencing setup.

Booking page slots

const { timezone, slots } = await shipmail.bookingPages.slots("bkp_123", {
  from: "2026-11-09T00:00:00Z",
  to: "2026-11-16T00:00:00Z",
});

Returns the open slots the page offers, exactly as its public page shows them, as UTC instants, with the page's timezone. Both bounds are optional: the window runs from now to the end of the page's booking horizon, at most 62 days. Needs the calendar:read scope.

Newsletter workflow

Build newsletters you want to edit later out of blocks. Paragraph, quote, callout, list-item, and column bodies accept bare text or sanitized inline HTML. Use p and br for line breaks. Use body_html or custom_html only when you need raw HTML.

import { readFile } from "node:fs/promises";

// Set up sending once: publish domain.dns_records, then verify until status is "verified".
const domain = await shipmail.newsletters.domains.create({
  root_domain: "example.com",
  reply_to_address: "hello@example.com",
});
await shipmail.newsletters.domains.verify(domain.id);
await shipmail.newsletters.senderIdentities.create({
  newsletter_domain_id: domain.id,
  from_name: "Acme",
  business_name: "Acme Ltd.",
});

const senderIdentities = await shipmail.newsletters.senderIdentities.list({ limit: 25 });
const assets = await shipmail.newsletters.assets.list({
  kind: "image",
  q: "feature",
  limit: 25,
});
for await (const asset of shipmail.newsletters.assets.listAutoPaginating({
  kind: "image",
  q: "feature",
  limit: 25,
})) {
  console.log(asset.filename);
}
const image = await shipmail.newsletters.assets.upload({
  filename: "feature.png",
  content_type: "image/png",
  data: await readFile("feature.png"),
});
const existingImage = await shipmail.newsletters.assets.registerFromUrl({
  url: "https://cdn.shipmail.to/newsletter-images/org_123/demo.png",
  filename: "demo.png",
});

console.log(assets.storage.used_bytes, assets.storage.limit_bytes);

const newsletter = await shipmail.newsletters.create({
  audience_id: "aud_...",
  sender_identity_id: senderIdentities.data[0].id,
  name: "July changelog",
  subject: "What shipped in July",
  preview_text: "A quick product update",
  blocks: [
    { type: "heading", level: 1, text: "July updates" },
    {
      type: "callout",
      variant: "info",
      title: "Quick note",
      body: "A <strong>short</strong> intro.",
    },
    {
      type: "paragraph",
      body: 'Read the <a href="https://example.com/launch">full announcement</a>.',
    },
    { type: "image", url: image.url, alt: "Product screenshot" },
    { type: "image", url: existingImage.url, alt: "Existing CDN screenshot" },
    {
      type: "columns",
      ratio: "50-50",
      left: { title: "For teams", image_url: image.url, image_fit: "natural" },
      right: { title: "For agents", image_url: existingImage.url, image_fit: "contain" },
    },
  ],
});

await shipmail.newsletters.preview(newsletter.id);
await shipmail.newsletters.sendTest(newsletter.id, {
  recipient_email: "owner@example.com",
});
await shipmail.newsletters.preflight(newsletter.id);
await shipmail.newsletters.schedule(newsletter.id, {
  scheduled_at: "2026-08-01T09:00:00.000Z",
});

Preflight lists every URL in the issue. Too many clickable destinations is an error. A high number of remote resources (links, images, video thumbnails) is a warning.

Pass limit to send to the most engaged subscribers first, then send to the others with sendToMore. Set subject_b on create or update to test a second subject.

await shipmail.newsletters.update(newsletter.id, {
  subject_b: "July: three things you asked for",
  track_engagement: true,
});
await shipmail.newsletters.schedule(newsletter.id, {
  scheduled_at: "2026-08-01T09:00:00.000Z",
  limit: 500,
});

// A website-only issue: published on the newsletter website at the scheduled time, no email.
await shipmail.newsletters.update(newsletter.id, { publish_target: "website" });
await shipmail.newsletters.sendToMore(newsletter.id, { count: 1000 });

Retries

The SDK retries eligible requests after connection errors, 429 responses, and retryable 5xx errors. GET, HEAD and OPTIONS requests retry on their own. POST, PATCH and PUT retry only when you pass an explicit idempotencyKey method option or an Idempotency-Key header. Use the same key for every try of the same operation. DELETE requests and errors marked non-retryable are never retried.

maxRetries defaults to 2, for up to 3 total attempts, and must be a non-negative integer. Set it to 0 to disable retries. A valid Retry-After header, in seconds or HTTP-date format, wins over the rate-limit error body's retry_after. Without either, the SDK waits with exponential backoff and jitter. If the server asks for more than 60 seconds, the SDK returns the error instead of waiting. Retry yourself once that time has passed.

Error handling

API errors throw typed subclasses of ShipmailError. Each error exposes status, type, requestId, and retryable. When the organization owner can fix a refusal in Shipmail, the error also sets reason and actionUrl; send the link to the owner, then retry with a new idempotency key. When a plan, trial or fixed limit causes the refusal, it also sets limit with resource, used, limit and scope. Newsletter guardrail failures on test-send and schedule are ValidationErrors with preflight fields in details.

import Shipmail, {
  ValidationError,
  RateLimitError,
  ShipmailError,
} from "shipmail";

try {
  await shipmail.messages.send({ ... });
} catch (err) {
  if (err instanceof ValidationError) {
    console.log(err.details); // per-field errors
  } else if (err instanceof RateLimitError) {
    console.log(err.retryAfter); // seconds to wait
  } else if (err instanceof ShipmailError) {
    console.log(err.status, err.requestId);
  }
}
ClassStatus
AuthenticationError401
AuthorizationError403
ValidationError422
NotFoundError404
ConflictError409
RateLimitError429
InternalServerError500
ConnectionErrorNetwork failure

Pagination

List methods return one page of results with a pagination object. Every list method also has a listAutoPaginating variant that returns a Page implementing AsyncIterable. Loop over it with for await and it fetches each page for you:

for await (const domain of shipmail.domains.listAutoPaginating()) {
  console.log(domain.name);
}

Or call list with limit and cursor to page through yourself:

const page = await shipmail.domains.list({ limit: 10 });
// page.pagination.has_more, page.pagination.next_cursor

Webhook verification

The SDK exports a standalone verifyWebhook function. It is async because it imports crypto at runtime, so the same code works on every runtime.

import { verifyWebhook } from "shipmail";

const event = await verifyWebhook(
  rawBody,
  request.headers,
  process.env.WEBHOOK_SECRET,
);

console.log(event.event_type); // "message.received"

Throws WebhookVerificationError if the signature is invalid or the timestamp is more than 5 minutes off. Pass { toleranceInSeconds: 600 } to change the window.

Per-request options

Every method takes an optional last argument that overrides settings for that one request:

await shipmail.domains.create(
  { name: "example.com" },
  {
    idempotencyKey: "550e8400-...",
    timeout: 10_000,
    signal: AbortSignal.timeout(5000),
  },
);