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 shipmailMember 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);Attach files from disk
On Node.js and Bun, attachmentFromPath from shipmail/node reads a file into an inline attachment for messages.send. The filename is the file's name and the content type comes from its extension, or application/octet-stream when it is unknown. Pass filename or contentType to set them. The main shipmail entry never reads files, so browser bundles stay clean.
The whole email can be 10 MB with encoding, which leaves about 7 MB for files. A transactional sender takes inline files only. For larger files, stage each one with mailboxes.stageAttachment and send its ID in staged_attachment_ids.
import { attachmentFromPath } from "shipmail/node";
await shipmail.messages.send({
mailbox_id: "mbx_123",
to: ["customer@example.com"],
subject: "Invoice",
text: "Attached.",
attachments: [
await attachmentFromPath("./invoice.pdf"),
await attachmentFromPath("./export", { filename: "export.csv", contentType: "text/csv" }),
],
});Email held for review
An API key can hold email to outside addresses for review. With such a key, messages.send, messages.reply and threads.reply return a HeldMessage instead of a message when a recipient is outside your domains. Nothing was sent: the email waits in the mailbox's Drafts for a person to send. Check the result with isHeldMessage.
import Shipmail, { isHeldMessage } from "shipmail";
const result = await shipmail.messages.send({
from: "hello@yourdomain.com",
to: ["client@example.com"],
subject: "Proposal",
text: "Here is the proposal.",
});
if (isHeldMessage(result)) {
console.log("Saved as draft", result.draft_id, "for", result.external_recipients);
} else {
console.log("Sent", result.id);
}client_reference, metadata and track_reply stay with a held draft and apply to the message the person sends. result.client_reference tells you which of your records the draft belongs to.
Batch sends and reply state
messages.sendBatch sends up to 50 messages in one request and returns one result per item. Check each with isHeldMessage and isMessageBatchItemError. Thread objects carry attention_state and attention_since, and threads.list filters by them and by batch_id.
import Shipmail, { isHeldMessage, isMessageBatchItemError } from "shipmail";
const batch = await shipmail.messages.sendBatch(
{
messages: leads.map((lead) => ({
from: "sales@yourdomain.com",
to: [lead.email],
subject: "Quick question",
text: `Hi ${lead.name}, ...`,
client_reference: lead.id,
metadata: { campaign: "q4" },
track_reply: true,
})),
},
{ idempotencyKey: "q4-outreach-1" },
);
for (const item of batch.data) {
if (isMessageBatchItemError(item)) console.log("Refused", item.index, item.error.message);
else if (isHeldMessage(item)) console.log("Held", item.client_reference, item.draft_id);
else console.log("Sent", item.client_reference, item.id);
}
const silent = await shipmail.threads.list({
batch_id: batch.batch_id,
attention_state: "waiting_on_them",
before: "2026-11-05T00:00:00Z",
});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" },
});| Option | Default | Description |
|---|---|---|
| apiKey | required | Your sm_live_... key. |
| baseUrl | https://shipmail.to/api/v1 | API base URL. |
| maxRetries | 2 | Retry count for eligible requests; 0 disables retries. |
| timeout | 30000 | Request timeout in ms. |
| defaultHeaders | {} | Headers sent with every request. |
| fetch | globalThis.fetch | Your own fetch, for tests or a proxy. |
Resources
Each API resource is a property on the client:
| Property | Methods |
|---|---|
| shipmail.organization | access: plan, access, trial and mailbox capacity. See GET /v1/organization/access. get, update, getAiSettings, updateAiSettings: the default time zone and AI switches. |
| shipmail.domains | create, list, get, getDnsRecords, getHealth, update, delete, verify, search, register |
| shipmail.mailboxes | create, list, get, update, delete, listFolders, createFolder, updateFolder, deleteFolder, listIdentities, listInboxMessages, getInboxMessage, listInboxThreads, getInboxThread, updateInboxThreadAttention, createInboxDraft, getInboxDraft, downloadInboxMessageRaw, updateInboxDraft, deleteInboxDraft, createInboxReplyDraft, listInboxReplyDrafts, getInboxReplyDraft, updateInboxReplyDraft, deleteInboxReplyDraft, sendInboxReplyDraft, replyToInboxMessage, replyToInboxThread, updateInboxMessage, moveInboxMessage, deleteInboxMessage, downloadInboxAttachment, resetPassword, getRules, updateRules, listAliases, createAlias, deleteAlias, listForwarding, createForwarding, deleteForwarding, updateAutoReply, createExport, getExport, createImport, listImports, getImport, cancelImport, resumeImport, restoreImport, undoImport, createImportUpload |
| shipmail.replyScans | create, get, listResults |
| shipmail.messages | send (with a template or your own content), sendBatch, list (by mailbox, client reference or batch), get, reply, respondToInvitation |
| shipmail.templates | create, list, get, update, delete, publish, render, listVersions, getVersion, restoreVersion |
| shipmail.members | list, listAutoPaginating, get, listInvitations, invite, cancelInvitation, grantMailboxAccess, revokeMailboxAccess |
| shipmail.threads | list (by mailbox or batch, filtered by attention state), get, reply |
| shipmail.webhooks | create, list, get, update, delete, rotateSecret, test, listDeliveries |
| shipmail.eventQueues | create, list, listAutoPaginating, get, delete, listEvents, ack |
| shipmail.smtpCredentials | list (filter by from), create (returns the password once), revoke |
| shipmail.transactionalDomains | list, create, get, verify, delete |
| shipmail.transactionalSenders | list (filter by domain_id), create, get, update |
| shipmail.suppressions | create, list (filter by scope), remove, removeBatch, resubscribe (lift a newsletter opt-out) |
| shipmail.customers | list, get, create, update, remove, upsertByExternalId, listServiceLevels, listFields |
| shipmail.audiences | create, list, get, update, delete |
| shipmail.automations | create, list, get, update, run, test |
| shipmail.audiences.subscribers | add, addBatch, list, get, getByEmail, update, unsubscribe (scope organization or audience), resubscribe, resendConfirmation, remove |
| shipmail.audiences.feeds | get, update, rotate, revoke |
| shipmail.audiences.segments | list, create, get, update, delete |
| shipmail.newsletters | create, createFromChangelog, list, get, update, preview, preflight, sendTest, schedule, cancel, resume |
| shipmail.newsletters.domains | list |
| shipmail.newsletters.assets | list, upload, registerFromUrl |
| shipmail.calendar.events | create, list, get, update, delete |
| shipmail.calendar | availability |
| shipmail.bookingPages | create, list, get, update, delete |
| shipmail.bookingLinks | create, list, get, update, revoke |
| shipmail.status | get |
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 draftA 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.
Check a subscriber list before importing
const check = await shipmail.audiences.subscribers.addBatch("aud_123", {
subscribers: [{ email_address: "jane@example.com" }, { email_address: "alex@gamil.com" }],
dry_run: true,
});
for (const row of check.results) {
if (row.outcome === "skipped_invalid") {
console.log(row.email_address, row.reason, row.suggestion);
}
}Pass dry_run: true to see what an import would do. Each row gets the outcome it would have, and nothing is added, charged or sent. A skipped_invalid row carries a reason code, and a typo carries the corrected address in suggestion. A dry run does not check the subscriber limit, the monthly add quota or the API key's recipient limits.
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",
duration: 60,
});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. duration picks one of the lengths the page offers and defaults to its duration_minutes. Needs the calendar:read scope.
Booking page hours and lengths
await shipmail.bookingPages.update("bkp_123", {
duration_minutes: 30,
duration_options: [15, 30, 60],
weekly_hours: [
{ day: 1, start_minutes: 540, end_minutes: 720 },
{ day: 1, start_minutes: 780, end_minutes: 1020 },
],
max_bookings_per_day: 4,
reminder_minutes_before: 1440,
});weekly_hours allows up to 4 ranges a day, so a day can have a break, and replaces availability_days and the window. date_overrides sets time off and special hours. Set a limit or an email field to null to turn it off. See the booking pages API for every field.
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 });
// No View in browser link in this issue, or by default in new dashboard issues of the audience.
await shipmail.newsletters.update(newsletter.id, { view_in_browser: false });
await shipmail.audiences.update("aud_123", { view_in_browser_default: false });
// Track opens and clicks by default in new issues; skip the last-chance email in list cleanup.
await shipmail.audiences.update("aud_123", {
track_engagement_default: true,
cleanup_send_last_chance: false,
});
// New dashboard issues of the audience go to the website only, with UTM tags and a feed title link.
await shipmail.audiences.update("aud_123", {
publish_target_default: "website",
add_utm_tags_default: true,
feed_entry_url_default: "https://example.com/blog",
});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);
}
}| Class | Status |
|---|---|
| AuthenticationError | 401 |
| AuthorizationError | 403 |
| ValidationError | 422 |
| NotFoundError | 404 |
| ConflictError | 409 |
| RateLimitError | 429 |
| InternalServerError | 500 |
| ConnectionError | Network 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_cursorWebhook 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),
},
);Links
- Guides: send email from Next.js or Cloudflare Workers, or give a Vercel AI SDK or Mastra agent its own inbox
- npm
- Python SDK (sync and async clients for Python 3.10+).
- REST API reference for plain HTTP calls.