Skip to content

About

The official SMTPfast SDK for Node.js and TypeScript, generated from the OpenAPI spec

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

25 Commits

Folders and files

Repository files navigation

SMTPfast Node.js SDK

The official TypeScript and JavaScript SDK for the SMTPfast API. It covers every endpoint in the API, has full types, and has no runtime dependencies. It runs on Node.js 22+, Bun, Deno and edge runtimes.

npm install @smtpfast/sdk

Send an email

import { SMTPfast } from "@smtpfast/sdk";

const smtpfast = new SMTPfast(); // reads SMTPFAST_API_KEY

const email = await smtpfast.emails.send({
  from: "Acme <hello@yourdomain.com>",
  to: ["customer@example.org"],
  subject: "Your receipt",
  html: "<p>Thanks for your order.</p>",
  category: "transactional",
});
console.log(email.id);

Email is marketing unless you set category to transactional. Marketing email gets a one-click unsubscribe header and is not sent to people who unsubscribed. Set transactional on receipts, password resets and account alerts so a marketing opt-out does not block them.

Every API operation is a method, named after its path: smtpfast.domains.verify(id), smtpfast.contacts.segments.add(contactId, segmentId), smtpfast.inboxes.threads.emails.reply(inboxId, threadId, emailId, body). Path parameters come first, then the request body or the query, then options.

Options

const smtpfast = new SMTPfast({
  apiKey: "sf_...",          // default: process.env.SMTPFAST_API_KEY
  baseUrl: "https://smtpfa.st/api",
  maxRetries: 2,              // after 429 (with Retry-After), 408, 5xx and dropped connections
  timeout: 60_000,            // per attempt, in ms
});

// Per call:
await smtpfast.emails.send(body, { idempotencyKey: "order-1234", timeout: 10_000, signal });

Retries and idempotency

Reads, PUT and DELETE are retried after a 5xx answer or a dropped connection. A send, reply or forward is retried with the same Idempotency-Key, so the API returns the first answer instead of sending twice. When you do not give a key, the SDK makes one per call. Other POST and PATCH calls are retried only after a per-second rate limit, which the API rejects before doing any work.

Errors

Every error is an SMTPfastError. An answer outside 2xx throws an APIError with status, body and headers, as one of BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError or InternalServerError. No answer at all throws APIConnectionError or APITimeoutError.

import { NotFoundError } from "@smtpfast/sdk";

try {
  await smtpfast.emails.get("em_missing");
} catch (err) {
  if (err instanceof NotFoundError) console.log(err.status, err.body);
  else throw err;
}

Pagination

Lists that page with a cursor also have an ...All method that fetches the next pages as you iterate:

for await (const email of smtpfast.emails.listAll({ limit: 100 })) {
  console.log(email.id, email.status);
}

Webhooks

import { parseWebhook } from "@smtpfast/sdk";

// The raw body, before any JSON parsing.
const event = await parseWebhook({ payload: rawBody, headers: request.headers, secret: process.env.SMTPFAST_WEBHOOK_SECRET! });
if (event.type === "email.bounced") { /* ... */ }

verifyWebhookSignature({ payload, signature, secret }) returns a boolean if you only need the check.

Tools for AI agents

Ready-made email tools for the Vercel AI SDK (@smtpfast/sdk/ai) and the OpenAI Agents SDK (@smtpfast/sdk/openai-agents). Both give the same tools for one inbox, with zod schemas:

Tool What it does
create_draft Writes a new email as a draft. Nothing is sent.
list_inbox_threads Lists threads, newest first, with a short preview. Takes a folder, a search query and unread only.
get_thread Reads a thread: each message's addresses, where a reply goes, the SPF, DKIM, DMARC, spam and virus verdicts, warnings and the body.
reply_to_thread Writes a reply draft to the person who wrote the message (its Reply-To or From).
send_email Sends at once. Only there with allowDirectSend: true.

Writes are drafts by default: a person reviews them in the dashboard and sends them. With allowDirectSend: true, send_email is added and reply_to_thread sends at once.

npm install @smtpfast/sdk ai @ai-sdk/openai zod # Vercel AI SDK 7
npm install @smtpfast/sdk @openai/agents zod      # OpenAI Agents SDK 0.22
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
import { SMTPfast } from "@smtpfast/sdk";
import { smtpfastTools } from "@smtpfast/sdk/ai";

const tools = smtpfastTools(new SMTPfast(), { inbox: "support@yourdomain.com" });
const { text } = await generateText({
  model: openai("gpt-5-mini"),
  tools,
  stopWhen: stepCountIs(8),
  prompt: "Read the unread threads and draft a reply to each.",
});
import { Agent, run } from "@openai/agents";
import { SMTPfast } from "@smtpfast/sdk";
import { smtpfastTools } from "@smtpfast/sdk/openai-agents";

const agent = new Agent({
  name: "Support",
  instructions: "Answer support email. Write drafts; never promise refunds.",
  tools: smtpfastTools(new SMTPfast(), { inbox: "support@yourdomain.com" }),
});
const result = await run(agent, "Draft a reply to thread th_123.");

In CommonJS (require), @smtpfast/sdk/ai needs Node.js 22.12 or later, because ai is an ES module.

Options: inbox (id or address, required), allowDirectSend, from (the From of send_email; defaults to the inbox's address and name), tools (a subset by name), maxBodyChars (8000), maxMessages (20) and dashboardUrl.

When the API refuses, a tool returns { ok: false, error: { status, code, message, hint } } instead of throwing, so the model can read why: for example a 403 for a missing scope, a 404 for a wrong thread id, or a 429 with retry_after_seconds. The codes recipient_not_allowed (with the refused recipients), inbox_not_allowed and key_send_limit from keys with per-agent limits get their own hints. Connection failures come back the same way with the code connection_error or timeout.

Email is written by strangers. Outside the content blocks, the tools return bare addresses only; entries that are not plain addresses are left out. get_thread and list_inbox_threads put the full From, To, Cc and Reply-To headers, subjects, previews and bodies inside <untrusted_email_content id="..."> blocks with a random id per call, replace the tag name wherever it appears in the content (so an email cannot close the block), and add a security_note that tells the model to treat the blocks as data. This lowers the risk of prompt injection; it does not remove it. The real limit is the API key: give the agent a key without email:send, since writing drafts needs only inbound:read.

How this SDK is made

The SDK is generated from the OpenAPI document, so it follows the API without hand edits:

  • src/generated/ holds the typed request functions, made by @hey-api/openapi-ts.
  • src/resources.gen.ts holds the smtpfast.emails.send() layer, made by scripts/generate.mjs from the x-sdk-group and x-sdk-method names the spec gives every operation. The SDKs for other languages use the same names.
  • src/core.ts, src/errors.ts and src/webhooks.ts are written by hand: retries, errors, pagination and signature checks.
npm run spec:pull   # download the published spec into spec/openapi.json
npm run generate    # regenerate src/generated and src/resources.gen.ts
npm test            # unit tests, including one call per operation
SMTPFAST_API_KEY=sf_... npm run test:live   # read-only calls, checked against the spec

A daily workflow pulls the spec and opens a pull request when it changed.

Scheduled checks for the agent tools (run on a schedule or by hand, never for pull requests; a failure posts to Discord):

  • latest-frameworks.yml, weekly: the tests and type tests against the newest ai, @openai/agents and zod, on Node.js 22 and 24.
  • agent-tools-live.yml, weekly: npm run live:agent-tools lists, reads and drafts in SMTPfast's own CI inbox through the built package, then deletes the drafts. Its key has only inbound:read and is limited to that inbox, so it cannot send.
  • agent-tools-model.yml, monthly: npm run live:agent-model has one agent per framework answer a test email that tries a prompt injection, with a small model on DigitalOcean serverless inference. It skips without the DO_CI_MODEL_KEY secret.

License

MIT

About

The official SMTPfast SDK for Node.js and TypeScript, generated from the OpenAPI spec

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages