Node.js / TypeScript SDK
Install @craftintertech/mailcraft and send your first email from Node.js, with safe automatic retries and webhook signature verification.
The official SDK for Node.js 18+. Written in TypeScript, zero runtime dependencies (it uses the built-in fetch), ships ESM and CommonJS builds with type definitions.
Install
npm install @craftintertech/mailcraft
# or pnpm add / yarn add / bun add
Send your first email
Create an API key under Mail Agents → API Keys (scope email:send) and store it in the MAILCRAFT_API_KEY environment variable — never hard-code it.
import { MailCraft } from '@craftintertech/mailcraft';
const mailcraft = new MailCraft(); // reads MAILCRAFT_API_KEY
const res = await mailcraft.send(
{
from: 'Example Shop <no-reply@mail.example.com>',
to: 'customer@example.org',
subject: 'Order #10042 confirmed',
htmlbody: '<h1>Thanks for your order</h1><p>We are getting it ready.</p>',
textbody: 'Thanks for your order. We are getting it ready.',
},
{ idempotencyKey: 'order-10042-receipt' },
);
console.log(res.message_id, res.credits_remaining);
CommonJS works too: const { MailCraft } = require('@craftintertech/mailcraft');
- Field names match the REST API (
htmlbody,textbody,reply_to,mime_headers, …). - Addresses can be
"Name <a@b.com>"strings or{ address, name }objects, single or in arrays. frommust be on a sending domain you have verified.
Attachments
Pass a Buffer or Uint8Array and the SDK base64-encodes it for you (a string must already be base64).
import { readFile } from 'node:fs/promises';
await mailcraft.send({
from: 'billing@mail.example.com',
to: 'customer@example.org',
subject: 'Receipt INV-001',
textbody: 'Your receipt is attached.',
attachments: [
{ name: 'INV-001.pdf', content: await readFile('INV-001.pdf'), mime_type: 'application/pdf' },
],
});
Templates, scheduling, batches and cancel
const r = await mailcraft.send({
from: 'hello@mail.example.com',
to: { address: 'somchai@example.org', name: 'Somchai' },
template_alias: 'welcome',
template_data: { name: 'Somchai' },
send_at: new Date('2027-01-02T02:00:00Z'),
list_unsubscribe: true,
});
await mailcraft.cancel(r.message_id); // before it is sent
await mailcraft.sendBatch([
{ from: 'hello@mail.example.com', to: 'a@example.org', template_alias: 'welcome', template_data: { name: 'A' } },
{ from: 'hello@mail.example.com', to: 'b@example.org', template_alias: 'welcome', template_data: { name: 'B' } },
]);
const status = await mailcraft.get(r.message_id); // per-recipient delivery status
Errors
Every error is a MailCraftError with status, code, field, retryAfter and body.
import { MailCraftError, InsufficientCreditsError, PermissionDeniedError } from '@craftintertech/mailcraft';
try {
await mailcraft.send(message);
} catch (err) {
if (err instanceof InsufficientCreditsError) {
console.error(`Balance ${err.balance}, required ${err.required}`);
} else if (err instanceof PermissionDeniedError && err.code === 'sandbox_restricted') {
// account is still in sandbox mode
} else if (err instanceof MailCraftError) {
console.error(err.status, err.code, err.message);
} else {
throw err;
}
}
| HTTP | Class / code |
|---|---|
| 400 / 422 | ValidationErrorinvalid_input |
| 401 | AuthenticationErrorunauthorized |
| 402 | InsufficientCreditsErrorinsufficient_credits |
| 403 | PermissionDeniedErrorsandbox_restricted, missing_scope, forbidden |
| 409 | ConflictErroridempotency_key_reused |
| 413 | PayloadTooLargeErrormessage_too_large |
| 429 | RateLimitErrorrate_limited |
| 5xx | ServerErrorserver_error |
| — | ConnectionErrornetwork_error, timeout, aborted |
Automatic retries
429, 500, 502, 503, 504 and network errors are retried up to 2 times, waiting for Retry-After when present and using exponential backoff with jitter otherwise.
Sends always carry an Idempotency-Key (generated for you unless you pass one), so a retry never delivers twice and never charges twice. Prefer your own stable reference, such as an order number, so deduplication also survives app restarts.
const mailcraft = new MailCraft({
apiKey: process.env.MAILCRAFT_API_KEY,
timeout: 30_000, // ms per attempt
maxRetries: 2, // 0 disables retries
maxRetryDelay: 60_000, // a longer Retry-After throws RateLimitError instead of waiting
});
Verify webhooks
See Verify webhook signatures for the full guide.
import { parseEvent } from '@craftintertech/mailcraft';
const event = parseEvent(rawBody, req.headers['mailcraft-signature'], process.env.MAILCRAFT_WEBHOOK_SECRET!);