Skip to content
Mailbit

Mailbit documentation

Mailbit is a transactional email API. You send email with a single HTTP request or with the @mailbit/node SDK; we sign it with your domain's DKIM key, deliver it from our own mail servers and report back every delivery event through signed webhooks.

All requests go to https://api.mailbit.dev. Request and response bodies are JSON. The dashboard lives at https://app.mailbit.dev.

Quickstart

1. Install the SDK

npm i @mailbit/node

2. Send your first email

Create an API key in the dashboard and expose it as MAILBIT_API_KEY. The domain of the from address must exactly match a verified domain.

send.ts
import { Mailbit } from "@mailbit/node";

const Mailbit = new Mailbit(process.env.MAILBIT_API_KEY);

const { data, error } = await mailbit.emails.send({
  from: "Acme <hello@acme.com>",
  to: ["user@example.com"],
  subject: "Welcome",
  html: "<p>Hi!</p>",
});

if (error) {
  console.error(error.statusCode, error.type, error.message);
} else {
  console.log(data.id); // "em_7fQk2LmNpR4sTvWx"
}

SDK methods never throw for API errors. They resolve to { data, error }, where exactly one of the two is null and error is { type, message, statusCode }.

The API key argument is optional and falls back to MAILBIT_API_KEY. A second argument configures the client:

const mailbit = new Mailbit(undefined, {
  baseUrl: "https://api.mailbit.dev", // default
  timeout: 30_000, // per request, in ms
  maxRetries: 2, // retries network errors, 429 and 5xx on GET, DELETE and idempotent requests
});

3. Or use curl

terminal
curl -X POST https://api.mailbit.dev/emails \
  -H "Authorization: Bearer mb_..." \
  -H "Content-Type: application/json" \
  -d '{
    "from": "Acme <hello@acme.com>",
    "to": ["user@example.com"],
    "subject": "Welcome",
    "html": "<p>Hi!</p>"
  }'
201 Created
{ "id": "em_7fQk2LmNpR4sTvWx" }

Authentication

Authenticate every request with an API key in the Authorization header. Keys start with mb_ and are shown only once, when created.

Authorization: Bearer mb_3fQ9wZkR...

Keys come in two permission levels:

  • full_access — can call every endpoint, including domains, API keys and webhooks.
  • sending_access — can only send (POST /emails and POST /emails/batch). Optionally restricted to a single domain.

Requests are rate limited per key (10 requests per second by default). Responses carry ratelimit-limit and ratelimit-remaining headers; a 429 also sets retry-after.

Errors

Errors use conventional HTTP status codes and always share the same body shape. In the SDK the same object is returned as error.

422 Unprocessable Entity
{
  "error": {
    "type": "validation_error",
    "message": "to: must contain between 1 and 50 recipients"
  }
}

Error types

validation_error
422The request body or query is invalid.
missing_api_key
401No Authorization header was sent.
invalid_api_key
403The API key is unknown or was revoked.
restricted_api_key
403The key is sending-only, or restricted to a different domain.
domain_not_verified
403The from domain does not exactly match a verified domain.
not_found
404The resource does not exist.
conflict
409The resource already exists, e.g. a duplicate domain.
idempotency_conflict
409The idempotency key was reused with a different request body.
invalid_state
409The action is not possible right now, e.g. cancelling an email that already went out.
rate_limit_exceeded
429Too many requests. Wait for the number of seconds in retry-after.
internal_error
500Something went wrong on our side.

Idempotency

POST /emails and POST /emails/batch accept an Idempotency-Key header. If a request with the same key was already processed in the last 24 hours, the original response is replayed with an idempotent-replayed: true header and no new email is sent, so you can retry network failures safely. Reusing a key with a different body returns 409 idempotency_conflict.

await mailbit.emails.send(
  { from, to, subject, html },
  { idempotencyKey: `welcome-${user.id}` },
);
Idempotency-Key: welcome-user_123

Emails

Send an email

POST/emails

Queue a single email for delivery. Returns the email ID immediately.

Body parameters

fromrequired
stringSender address. Its domain must exactly match a verified domain. Use Name <address> to set a display name.
torequired
string | string[]Recipient address or addresses. Max 50.
cc
string | string[]Carbon copy recipients.
bcc
string | string[]Blind carbon copy recipients.
replyTo
string | string[]Address(es) used for replies.
subjectrequired
stringEmail subject line.
html
stringHTML body. At least one of html or text is required.
text
stringPlain-text body.
headers
Record<string, string>Custom headers, e.g. { "X-Entity-Ref-ID": "123" }.
attachments
{ filename, content, contentType }[]Files to attach. content is base64-encoded (the SDK also accepts a Buffer or Uint8Array and encodes it for you); contentType is optional.
tags
{ name, value }[]Key/value pairs to label the email. Tags are searchable in logs and included in webhook events.
scheduledAt
string (ISO 8601)Send at a future time, up to 30 days ahead, e.g. 2026-11-20T09:00:00Z. The SDK also accepts a Date. Scheduled emails can be cancelled until they go out.
request
const { data, error } = await mailbit.emails.send({
  from: "Acme <billing@acme.com>",
  to: "user@example.com",
  replyTo: "support@acme.com",
  subject: "Your invoice",
  html: "<p>Invoice attached.</p>",
  attachments: [
    { filename: "invoice.pdf", content: pdfBase64, contentType: "application/pdf" },
  ],
  headers: { "X-Entity-Ref-ID": "inv_4821" },
  tags: [{ name: "category", value: "billing" }],
  scheduledAt: "2026-11-20T09:00:00Z",
});
201 Created
{ "id": "em_7fQk2LmNpR4sTvWx" }

Send a batch

POST/emails/batch

Send up to 100 emails in one request. The body is an array of objects with the same fields as Send an email. Attachments and scheduledAt are not supported in batches. Accepts an Idempotency-Key too.

request
const { data, error } = await mailbit.emails.batch([
  { from: "Acme <hello@acme.com>", to: "a@example.com", subject: "Hi A", text: "..." },
  { from: "Acme <hello@acme.com>", to: "b@example.com", subject: "Hi B", text: "..." },
]);
201 Created
{
  "data": [
    { "id": "em_3HbZ9xKcWq2eMn6T" },
    { "id": "em_8JdR4vYpLs5kAu2G" }
  ]
}

Retrieve an email

GET/emails/:id

Fetch a single email, including its bodies, current status and full event timeline. Requires a full_access key.

const { data } = await mailbit.emails.get("em_7fQk2LmNpR4sTvWx");
200 OK
{
  "object": "email",
  "id": "em_7fQk2LmNpR4sTvWx",
  "from": "Acme <hello@acme.com>",
  "to": ["user@example.com"],
  "cc": [],
  "bcc": [],
  "replyTo": [],
  "subject": "Welcome",
  "status": "delivered",
  "tags": [{ "name": "category", "value": "onboarding" }],
  "error": null,
  "scheduledAt": null,
  "sentAt": "2026-11-16T10:19:58.410Z",
  "createdAt": "2026-11-16T10:19:58.120Z",
  "html": "<p>Hi!</p>",
  "text": null,
  "events": [
    { "type": "sent", "recipient": null, "data": {}, "createdAt": "2026-11-16T10:19:58.410Z" },
    { "type": "delivered", "recipient": "user@example.com", "data": {}, "createdAt": "2026-11-16T10:20:00.002Z" }
  ]
}

status is one of scheduled, queued, canceled, sent, delivery_delayed, delivered, bounced, failed or complained.

List emails

GET/emails

List emails, newest first, without bodies or events. Requires a full_access key. To get the next page, pass the id of the last item as after while hasMore is true.

Query parameters

limit
number1–100. Defaults to 20.
after
stringReturn items after this email ID.
const { data } = await mailbit.emails.list({ limit: 50, after: "em_7fQk2LmNpR4sTvWx" });
200 OK
{
  "object": "list",
  "data": [
    { "object": "email", "id": "em_3HbZ9xKcWq2eMn6T", "subject": "Welcome", "status": "delivered", "...": "..." }
  ],
  "hasMore": true
}

Cancel a scheduled email

POST/emails/:id/cancel

Cancel an email that was sent with scheduledAt and has not gone out yet. Returns the email with status canceled, or 409 invalid_state if it is no longer scheduled.

await mailbit.emails.cancel("em_7fQk2LmNpR4sTvWx");
200 OK
{ "object": "email", "id": "em_7fQk2LmNpR4sTvWx", "status": "canceled", "...": "..." }

Domains

Before you can send from an address, its domain must be verified. Each domain gets its own 2048-bit DKIM key (with a selector like mbk3x9qa), an MX and an SPF record on a return-path subdomain (send.yourdomain.com by default) and a recommended DMARC record. The from domain of every email must exactly match a verified domain. All domain endpoints require a full_access key.

Add a domain

POST/domains

Body parameters

namerequired
stringThe domain, e.g. acme.com.
returnPathSubdomain
stringSubdomain used for the envelope sender and bounces. Defaults to send.
const { data } = await mailbit.domains.create({ name: "acme.com" });
201 Created
{
  "object": "domain",
  "id": "dom_5NcX8qTzWm3bHf7K",
  "name": "acme.com",
  "status": "pending",
  "returnPath": "send.acme.com",
  "records": [
    {
      "purpose": "dkim", "type": "TXT", "name": "mbk3x9qa._domainkey.acme.com",
      "value": "v=DKIM1; k=rsa; p=MIIBIjAN...", "required": true, "status": "pending"
    },
    {
      "purpose": "return_path_mx", "type": "MX", "name": "send.acme.com",
      "value": "smtp.mailbit.dev", "priority": 10, "required": true, "status": "pending"
    },
    {
      "purpose": "spf", "type": "TXT", "name": "send.acme.com",
      "value": "v=spf1 include:spf.mailbit.dev ~all", "required": true, "status": "pending"
    },
    {
      "purpose": "dmarc", "type": "TXT", "name": "_dmarc.acme.com",
      "value": "v=DMARC1; p=none; rua=mailto:dmarc@acme.com", "required": false, "status": "pending"
    }
  ],
  "createdAt": "2026-11-16T10:00:00.000Z",
  "lastCheckedAt": null,
  "verifiedAt": null
}
Start with p=none for DMARC, watch the aggregate reports, then move to quarantine or reject once all your legitimate mail is aligned.

List domains

GET/domains

Returns { "object": "list", "data": [...], "hasMore": false }.

const { data } = await mailbit.domains.list();

Retrieve a domain

GET/domains/:id

Returns the domain with its DNS records and the verification status of each.

const { data } = await mailbit.domains.get("dom_5NcX8qTzWm3bHf7K");

Verify a domain

POST/domains/:id/verify

Trigger a DNS check right away. We also re-check pending domains automatically in the background.

const { data } = await mailbit.domains.verify("dom_5NcX8qTzWm3bHf7K");
200 OK
{ "object": "domain", "id": "dom_5NcX8qTzWm3bHf7K", "status": "verified", "...": "..." }

Delete a domain

DELETE/domains/:id

Removes the domain and its DKIM key. Emails from this domain will be rejected afterwards.

await mailbit.domains.remove("dom_5NcX8qTzWm3bHf7K");
200 OK
{ "object": "domain", "id": "dom_5NcX8qTzWm3bHf7K", "deleted": true }

API keys

Create an API key

POST/api-keys

Body parameters

namerequired
stringA label to recognise the key.
permission
"full_access" | "sending_access"Defaults to full_access.
domainId
stringRestrict a sending_access key to one domain. Only valid for sending_access.
const { data } = await mailbit.apiKeys.create({
  name: "production",
  permission: "sending_access",
  domainId: "dom_5NcX8qTzWm3bHf7K",
});
201 Created
{
  "object": "api_key",
  "id": "api_2Gw9RkLp4ZsVx7Nd",
  "name": "production",
  "prefix": "mb_3fQ9",
  "permission": "sending_access",
  "domainId": "dom_5NcX8qTzWm3bHf7K",
  "lastUsedAt": null,
  "createdAt": "2026-11-16T10:05:00.000Z",
  "token": "mb_3fQ9wZkR..."
}
The token is only returned once. Store it in your secret manager right away.

List API keys

GET/api-keys

Returns a list of key metadata (name, prefix, permission, domain, created and last-used time). Tokens are never returned again.

const { data } = await mailbit.apiKeys.list();

Delete an API key

DELETE/api-keys/:id

Revokes the key immediately.

await mailbit.apiKeys.remove("api_2Gw9RkLp4ZsVx7Nd");

Webhooks

Webhooks deliver email events to your endpoint as POST requests. Failed deliveries (non-2xx or timeout) are retried for up to 8 attempts with exponential backoff, and every attempt is recorded in the webhook's delivery log in the dashboard. Webhook endpoints require a full_access key.

Create a webhook

POST/webhooks

Body parameters

urlrequired
stringHTTPS endpoint to deliver events to.
eventsrequired
string[]Event types to subscribe to, e.g. ["email.delivered", "email.bounced"].
const { data } = await mailbit.webhooks.create({
  url: "https://acme.com/webhooks/mailbit",
  events: ["email.delivered", "email.bounced", "email.complained"],
});
201 Created
{
  "object": "webhook",
  "id": "wh_6Tq3MzHc8YbKp2Rf",
  "url": "https://acme.com/webhooks/mailbit",
  "events": ["email.delivered", "email.bounced", "email.complained"],
  "enabled": true,
  "createdAt": "2026-11-16T10:10:00.000Z",
  "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
}
The secret is only returned once. Store it as MAILBIT_WEBHOOK_SECRET.

List webhooks

GET/webhooks
const { data } = await mailbit.webhooks.list();

Retrieve a webhook

GET/webhooks/:id
const { data } = await mailbit.webhooks.get("wh_6Tq3MzHc8YbKp2Rf");

Update a webhook

PATCH/webhooks/:id

Body parameters

url
stringNew endpoint URL.
events
string[]Replaces the subscribed event types.
enabled
booleanPause or resume deliveries.
await mailbit.webhooks.update("wh_6Tq3MzHc8YbKp2Rf", { enabled: false });

Delete a webhook

DELETE/webhooks/:id
await mailbit.webhooks.remove("wh_6Tq3MzHc8YbKp2Rf");

Event types

Events

email.sent
eventAccepted by our MTA and queued for delivery.
email.delivered
eventThe recipient's server accepted the message.
email.delivery_delayed
eventTemporarily deferred by the recipient's server. We keep retrying.
email.bounced
eventPermanently rejected. Hard bounces add the address to your suppression list.
email.complained
eventThe recipient marked the message as spam. The address is suppressed.
email.failed
eventThe email could not be sent, for example because the recipient is suppressed.

Payload

Every request carries three headers — webhook-id, webhook-timestamp and webhook-signature — and a JSON body:

email.delivered
{
  "type": "email.delivered",
  "createdAt": "2026-11-16T10:20:00.002Z",
  "data": {
    "emailId": "em_7fQk2LmNpR4sTvWx",
    "from": "Acme <hello@acme.com>",
    "to": ["user@example.com"],
    "subject": "Welcome",
    "tags": [{ "name": "category", "value": "onboarding" }],
    "createdAt": "2026-11-16T10:19:58.120Z",
    "recipient": "user@example.com"
  }
}

Depending on the event, data also carries a bounce object (email.bounced), a delay object (email.delivery_delayed) or a failure object (email.failed):

email.bounced
{
  "type": "email.bounced",
  "createdAt": "2026-11-16T10:20:01.530Z",
  "data": {
    "emailId": "em_7fQk2LmNpR4sTvWx",
    "from": "Acme <hello@acme.com>",
    "to": ["nobody@example.com"],
    "subject": "Welcome",
    "tags": [],
    "createdAt": "2026-11-16T10:19:58.120Z",
    "recipient": "nobody@example.com",
    "bounce": { "type": "hard", "dsn": "5.1.1", "diagnostic": "550 5.1.1 User unknown" }
  }
}

Hard bounces and complaints add the address to your team's suppression list. Later emails skip suppressed recipients.

Verifying signatures

Signatures follow the Standard Webhooks scheme: webhook-id is a message ID like msg_4Lx7NpQz2KcWm9Ts, and webhook-signature is v1,<base64 HMAC-SHA256> of ${webhook-id}.${webhook-timestamp}.${body}, keyed with your webhook secret. Always verify against the raw request body.

verifyWebhook() is async, returns the parsed event and throws a WebhookVerificationError if a header is missing, the signature does not match, or the timestamp is outside toleranceSeconds (default 300).

app/api/webhooks/mailbit/route.ts
import { verifyWebhook, WebhookVerificationError } from "@mailbit/node";

export async function POST(req: Request) {
  const rawBody = await req.text();

  try {
    const event = await verifyWebhook({
      payload: rawBody,
      headers: req.headers,
      secret: process.env.MAILBIT_WEBHOOK_SECRET!,
    });

    if (event.type === "email.bounced") {
      // mark the address as undeliverable in your app
    }

    return new Response(null, { status: 204 });
  } catch (err) {
    if (err instanceof WebhookVerificationError) {
      return new Response("invalid signature", { status: 400 });
    }
    throw err;
  }
}
Respond with a 2xx quickly and do heavy work asynchronously. Use webhook-id to de-duplicate, since retries can deliver the same event more than once.