# Charchy Send > Transactional email for your app — sign-in codes, password resets, receipts and order updates — sent from your own domain. Source: https://charchy.krd/docs Charchy Send is an email API. Your server calls one endpoint; the email leaves from your own domain, signed with your DKIM key. Every email's life shows in the dashboard and reaches your server as signed webhooks. ```ts import { CharchySend } from "@charchy/send" const send = new CharchySend() // reads CHARCHY_SEND_KEY await send.emails.send( { from: "Darin Game ", to: "customer@example.com", subject: "Your sign-in code: 482910", text: "Your code is 482910. It expires in 10 minutes.", }, { idempotencyKey: "signin-code/1842" } ) ``` ```bash curl https://api.charchy.krd/v1/emails \ -H "Authorization: Bearer $CHARCHY_SEND_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: signin-code/1842" \ -d '{ "from": "Darin Game ", "to": ["customer@example.com"], "subject": "Your sign-in code: 482910", "text": "Your code is 482910. It expires in 10 minutes." }' ``` ```json { "id": "em_8f2k1x9q4w7m3n5p6r0s2t4v", "status": "queued" } ``` ## What it is for **Transactional** email — mail a person's own action or account triggers: * Sign-in and verification codes * Password resets * Receipts and invoices * Order, shipping and booking confirmations * Account alerts Newsletters, offers and announcements are marketing: they go through [Charchy Campaigns](https://charchy.krd/pricing), not this API. See [Sending emails](/docs/sending-emails) for where the line is. ## Why Charchy Send * **Kurdish and Arabic work** in the subject, the body and the sender's display name (`"دارین گەیم "`). * **Built for codes that expire.** Set [`expires_at`](/docs/scheduling#expires_at); if the email can't leave in time, we drop and refund it. A sign-in code 20 minutes late is worse than none. * **Free test mode.** Test keys and the `@sim.charchy.krd` [magic addresses](/docs/test-mode) let you build and run CI without sending a real email or spending a credit. * **A lower price at volume.** [Pricing](/docs/pricing) starts at $9 a month. ## How it works 1. **Add your domain** and publish three DNS records (or click **Add with Cloudflare**). [Domains & DNS](/docs/domains) 2. **Create an API key.** Test keys start with `chy_test_`, live keys with `chy_live_`. Server only — never in browser or mobile code. 3. **Send** with `POST /v1/emails`, or up to 100 at once with [`POST /v1/emails/batch`](/docs/batch). 4. **Listen** for `email.delivered`, `email.bounced` and the other [webhook events](/docs/webhooks), or read an email's timeline with `GET /v1/emails/{id}`. ## The basics | | | | -------------- | ----------------------------------------------------------------------------------------------- | | Base URL | `https://api.charchy.krd/v1` | | Authentication | `Authorization: Bearer ` | | Format | JSON in, JSON out, UTF-8 | | Duplicates | Send an [`Idempotency-Key`](/docs/idempotency) header on every request | | Errors | `{ "error": { "code", "message", "docs" } }` — every code is on the [Errors](/docs/errors) page | | Rate limit | 10 requests a second per workspace, bursts of 20 | ## Getting access Charchy Send is **invite-only** for now: we set up each client by hand and check your domain and first emails before you go live. [Request access](/docs/request-access) — your website, what your app sends and how many emails a month. Approved requests get an invitation by email. Test mode is free while you build. --- # Sending emails > Which emails go through Charchy Send, which go through Charchy Campaigns, and how to tell. Source: https://charchy.krd/docs/sending-emails Charchy sends two kinds of email through two different doors. Using the right one keeps your important emails in the inbox. ## Transactional emails — Charchy Send One email to **one person**, because of **something they did** or something that happened to their account. They expect it and would be worse off without it. * Sign-in and verification codes * Password resets * Order confirmations, receipts and invoices * Shipping and booking updates * Account notices: a plan renewing, a security alert, a teammate's invite Send them with [`POST /v1/emails`](/docs/send-email), or up to 100 different ones at once with [`POST /v1/emails/batch`](/docs/batch) — a receipt for every order in an import, a reminder for every booking tomorrow. ## Marketing emails — Charchy Campaigns One email to **many people at once**, because **you** decided to send it. * Newsletters and product updates * Offers, discounts and sales * Announcements and event invitations Marketing needs the recipient's consent, an unsubscribe link in every email, and a reputation kept apart from your sign-in codes. Charchy Campaigns, in the Charchy dashboard, handles all three. Marketing email does not go through the API. ## The grey area Some emails look personal but are still marketing. The test: **would the person miss it if it never came?** | Email | Kind | Why | | ------------------------------------------- | -------------------------------- | ---------------------------------------------------------------- | | Abandoned-cart reminder | Marketing → Campaigns | One-to-one, but its job is to sell; the person didn't ask for it | | "We miss you" / win-back | Marketing → Campaigns | Sent because of what the person *didn't* do | | A product they viewed is on sale | Marketing → Campaigns | A promotion, however personal | | Receipt that also mentions a sale | Transactional → Send | The receipt is the point; keep the promotion small | | A reminder for each of 80 bookings tomorrow | Transactional → Send, as a batch | 80 different emails, each about that person's own booking | | One identical announcement to 80 customers | Marketing → Campaigns | The same email to many people is a campaign | When in doubt, write to [support@charchy.krd](mailto:support@charchy.krd) before you send. [What counts as transactional](/docs/transactional) explains how we check. ## Where to next --- # Quickstart > Send your first email in five minutes with a test key — curl, Node/TypeScript, Laravel, Python or Go. Source: https://charchy.krd/docs/quickstart You need a Charchy Send workspace. It is invite-only for now — [request access](/docs/request-access). Copy a ready prompt for Next.js, Convex, Laravel, Express or Django from [Build with AI](/docs/build-with-ai). It covers everything on this page. ### Get a test key Your welcome screen has a **test key** ready (`chy_test_…`); make more under **API keys**. A test key goes through every check a live key does but never sends a real email, and it is free. Put it in your server's environment: ```bash export CHARCHY_SEND_KEY="chy_test_…" ``` Keys belong on your server. The API sends no CORS headers, so a call from browser code fails — on purpose. ### Send an email Send to `delivered@sim.charchy.krd`, a [magic address](/docs/test-mode#magic-addresses) that always "delivers". With a test key, `from` can use any domain. ```ts // npm install @charchy/send — or plain fetch: it is one JSON POST. import { CharchySend } from "@charchy/send" const send = new CharchySend() // reads CHARCHY_SEND_KEY when a request is made const { data, error } = await send.emails.send( { from: "My App ", to: "delivered@sim.charchy.krd", subject: "Hello from Charchy Send", html: "

It works.

", }, { idempotencyKey: "quickstart/1" } ) if (error) throw error // error.code, error.message, error.docs console.log(data.id) // "em_…" ``` ```bash curl https://api.charchy.krd/v1/emails \ -H "Authorization: Bearer $CHARCHY_SEND_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: quickstart/1" \ -d '{ "from": "My App ", "to": ["delivered@sim.charchy.krd"], "subject": "Hello from Charchy Send", "html": "

It works.

" }' ``` ```php // .env: CHARCHY_SEND_KEY=chy_test_… // config/services.php: 'charchy_send' => ['key' => env('CHARCHY_SEND_KEY')], use Illuminate\Support\Facades\Http; $response = Http::withToken(config('services.charchy_send.key')) ->withHeaders(['Idempotency-Key' => 'quickstart/1']) ->acceptJson() ->post('https://api.charchy.krd/v1/emails', [ 'from' => 'My App ', 'to' => ['delivered@sim.charchy.krd'], 'subject' => 'Hello from Charchy Send', 'html' => '

It works.

', ]) ->throw(); echo $response->json('id'); // "em_…" — try it in php artisan tinker ``` ```python import os import requests response = requests.post( "https://api.charchy.krd/v1/emails", headers={ "Authorization": f"Bearer {os.environ['CHARCHY_SEND_KEY']}", "Idempotency-Key": "quickstart/1", }, json={ "from": "My App ", "to": ["delivered@sim.charchy.krd"], "subject": "Hello from Charchy Send", "html": "

It works.

", }, timeout=30, ) response.raise_for_status() print(response.json()["id"]) # "em_…" ``` ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" "os" ) func main() { body, _ := json.Marshal(map[string]any{ "from": "My App ", "to": []string{"delivered@sim.charchy.krd"}, "subject": "Hello from Charchy Send", "html": "

It works.

", }) req, _ := http.NewRequest("POST", "https://api.charchy.krd/v1/emails", bytes.NewReader(body)) req.Header.Set("Authorization", "Bearer "+os.Getenv("CHARCHY_SEND_KEY")) req.Header.Set("Content-Type", "application/json") req.Header.Set("Idempotency-Key", "quickstart/1") res, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer res.Body.Close() var result struct { ID string `json:"id"` Status string `json:"status"` } json.NewDecoder(res.Body).Decode(&result) fmt.Println(res.StatusCode, result.ID) // 200 em_… } ``` The response comes back at once: ```json { "id": "em_8f2k1x9q4w7m3n5p6r0s2t4v", "status": "queued" } ``` ### Watch it arrive In **Emails** in the dashboard, the email appears once accepted, turns **sent**, then **delivered** a second later. Or ask the API (reading needs a key with full permission, like the welcome-screen one): ```ts const { data, error } = await send.emails.get("em_8f2k1x9q4w7m3n5p6r0s2t4v") console.log(data?.status) // "delivered" ``` ```bash curl https://api.charchy.krd/v1/emails/em_8f2k1x9q4w7m3n5p6r0s2t4v \ -H "Authorization: Bearer $CHARCHY_SEND_KEY" ``` Try `bounced@sim.charchy.krd` too, to see what your code does with a bounce. ### Add your domain Real emails leave from your own domain. In **Domains**, add it and publish the three DNS records shown — or press **Add with Cloudflare**. See [Domains & DNS](/docs/domains). ### Go live Create a **live key** (`chy_live_…`; you accept the Charchy Send terms first) and change `from` to an address on your verified domain. Until your workspace is approved, a live key sends only to your own team's addresses, up to 50 a day, free — enough to see a real email in your inbox. Once approved and paid, it sends to anyone. ## Next * Tell your server what happened to each email: [Webhooks](/docs/webhooks). * Never send an email twice: [Idempotency](/docs/idempotency). * Codes that expire: [`expires_at`](/docs/scheduling#expires_at). * Every field: [Send an email](/docs/send-email). --- # SDKs > Official Charchy Send libraries. Node and TypeScript today; any language works with plain HTTP. Source: https://charchy.krd/docs/sdks | Language | Package | Source | | | ----------------- | -------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------- | | Node / TypeScript | [`@charchy/send`](https://www.npmjs.com/package/@charchy/send) | [charchyy/charchy-send](https://github.com/charchyy/charchy-send) | [Docs](/docs/sdks/node) | | Laravel | No package needed: [the Laravel guide](/docs/guides/laravel) | — | — | The SDKs are open source (MIT) and generate their types from the same [OpenAPI file](/docs/openapi.yaml) these docs use. No SDK for your language? The API is one JSON `POST` with a bearer key: the [Quickstart](/docs/quickstart) shows curl, Laravel, Python and Go, and the [OpenAPI file](/docs/openapi.yaml) generates a typed client for any language. --- # Node.js and TypeScript > @charchy/send — the official SDK: typed, zero dependencies, retries that never send twice, a one-line webhook endpoint and end-to-end test helpers. Node 18+, Bun, Deno, Vercel Edge and Cloudflare Workers. Source: https://charchy.krd/docs/sdks/node ```bash npm install @charchy/send ``` ```bash pnpm add @charchy/send ``` ```bash yarn add @charchy/send ``` ```bash bun add @charchy/send ``` [npm](https://www.npmjs.com/package/@charchy/send) · [GitHub](https://github.com/charchyy/charchy-send) (MIT) · [Changelog](https://github.com/charchyy/charchy-send/blob/main/CHANGELOG.md) Zero dependencies, ESM and CommonJS, fully typed. Runs on Node 18+, Bun, Deno (`npm:@charchy/send`), Vercel (Node and Edge) and Cloudflare Workers. Server code only: the API sends no CORS headers, and the SDK warns if it finds itself in a browser. The key lives in a private field — logging the client shows `chy_live_…1a2b`, never the key. Creating the client never needs the key: it is read (the argument, else `CHARCHY_SEND_KEY`) on each request. A client at the top of a module is safe in `next build` and in deploys that load code without your secrets; with no key, a call returns `missing_api_key` and nothing is sent. ## Send an email ```ts import { CharchySend } from "@charchy/send" const send = new CharchySend() // reads CHARCHY_SEND_KEY when a request is made const { data, error } = await send.emails.send( { from: { name: "My App", email: "no-reply@myapp.com" }, to: send.test.address("delivered"), // "delivered@sim.charchy.krd" subject: "Hello from Charchy Send", html: "

It works.

", }, { idempotencyKey: "welcome/user-123" } ) if (error) throw error console.log(data.id) // "em_…" ``` Fields are the API's in camelCase (`replyTo`, `scheduledAt`, `expiresAt`, `contentType`), in and out — except keys inside `tags` and `headers`, which stay exactly as you write them. Every field: [Send an email](/docs/send-email). Addresses are a string (`"a@b.com"`, `"Name "`), `{ name, email }` or an array of them; the SDK quotes a name with a comma or quote so it can't split into two recipients, and keeps Kurdish and Arabic names as they are. Input is checked before anything is sent: line breaks in addresses, an `expiresAt` already past or not after `scheduledAt`, a malformed idempotency key or an id that isn't `em_…` come back as `validation_error` with `field`. ## Results, not exceptions Every method resolves to `{ data, error, headers, meta }`. `error` is a `CharchySendError` with `code`, `message`, `field`, `docs`, `statusCode`, `requestId` (quote it to support), `retryAfterSeconds`, and for a refused [batch](/docs/batch) `items` by index. `meta` is the headers that matter, parsed — `requestId`, `rateLimit` (`{ limit, remaining, resetSeconds }`) and `emailsRemaining` — and `headers` keeps them all, lower-cased. `code` is an [API error code](/docs/errors) or one of the SDK's own: | Code | Means | | ------------------------ | ------------------------------------------------------------------------------------------------- | | `network_error` | No answer: the connection failed, timed out or was aborted | | `invalid_response` | An answer that isn't the API's JSON — a proxy page, an empty body, or a redirect (never followed) | | `react_render_error` | `react` given, but `@react-email/render` is missing or the render threw | | `wait_timeout` | `emails.waitFor` ran out of time | | `wait_unexpected_status` | `emails.waitFor` saw the email end canceled, expired, failed or unknown | ```ts import { unwrap } from "@charchy/send" // Prefer exceptions? unwrap returns data or throws the CharchySendError. const { id } = await send.emails.send({ from, to, subject: "Receipt", text: "Thanks!" }).then(unwrap) ``` ## Retries and idempotency Up to `maxRetries` extra attempts (default 2), jittered backoff: | Answer | Retried? | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `429`, `409 idempotency_in_flight` | After `Retry-After` — unless it is over 60 seconds (a [daily cap](/docs/rate-limits#daily-caps) comes back at once) | | Network error, timeout, `5xx` | Sends, reads, reschedule and cancel. Not image uploads | | `402 insufficient_balance`, every other `4xx`, a redirect | Never | **A retry never sends twice:** `emails.send` and `emails.batch` without an `idempotencyKey` get a random one on the first attempt, reused by every retry of that call. It covers the SDK's own retries only — a second call is a new email. Pass your own key, built from the event behind the email, and your job retries are safe too ([Idempotency](/docs/idempotency)): ```ts await send.emails.send({ from, to, subject: "Order confirmed", html }, { idempotencyKey: `order-confirmation/${order.id}` }) ``` ## Every method ```ts // One email: addresses as strings or { name, email }; Date, ISO or "10m"/"2h"/"1d" for times. await send.emails.send({ from, to, cc, bcc, replyTo, subject, html, text, tags, headers, scheduledAt: "1d", expiresAt: "26h", attachments }) // Up to 100 emails, no attachments, all accepted or none. await send.emails.batch(users.map((user) => ({ from, to: user.email, subject, html })), { idempotencyKey: "weekly-receipts/2026-W47" }) await send.emails.get("em_…") // status, recipients, events await send.emails.waitFor("em_…", { until: ["delivered"] }) // reads until then: for tests and CI await send.emails.list({ limit: 50, status: "bounced", tag: "type:order", to: "a@b.com" }) for await (const email of send.emails.listAll({ status: "bounced" })) {} // follows next_cursor; throws on a failed page await send.emails.update("em_…", { scheduledAt: "2026-11-20T08:00:00+03:00" }) await send.emails.cancel("em_…") await send.images.upload(await readFile("logo.png"), { filename: "logo.png" }) // → { id, url, contentType, size } await send.usage.get() // plan, credits, daily { cap, surgeCap, used, resetsAt }, test ``` * **Durations** (`"30s"`, `"10m"`, `"2h"`, `"1d"`) become an ISO time with your server's clock; the API itself takes [ISO 8601](/docs/scheduling) only. * **Attachments** take `Buffer`, `Uint8Array`, `ArrayBuffer`, `Blob` or a base64 string; `contentType` is inferred for common extensions (pdf, png, jpg, gif, webp, txt, csv, ics, html, json, zip). * **React Email:** `react: ` is rendered to `html` with `@react-email/render` (`npm install @react-email/render`, an optional peer). * Every method takes `{ signal }` to abort it and its retries. ## Test end to end ```ts console.log(send.mode) // "test" (chy_test_ key), "live", or null while there is no valid key const { id } = await send.emails .send({ from, to: send.test.address("bounced", "signup-42"), subject: "Test", text: "t" }) .then(unwrap) const { data, error } = await send.emails.waitFor(id, { until: ["bounced"], timeoutMs: 30_000 }) ``` `send.test.address(outcome, label?)` builds a [magic address](/docs/test-mode#magic-addresses) — `"delivered"`, `"bounced"`, `"complained"`, `"suppressed"` or `"delayed"`, with an optional label of letters, digits, `_` and `-`. `waitFor` reads the email until it reaches a status in `until` (default: any status it ends in), every `intervalMs` (1 s), for up to `timeoutMs` (60 s). It returns `wait_timeout` when time runs out and `wait_unexpected_status` at once when the email ends canceled, expired, failed or unknown instead. ## Webhook endpoint in one line `webhookHandler` (also `send.webhooks.handler`) is a complete endpoint — a standard `(request: Request) => Promise` for the Next.js App Router, Cloudflare Workers, Bun, Deno and Hono. One typed function per event you care about: ```ts // app/api/webhooks/charchy/route.ts import { webhookHandler } from "@charchy/send" export const POST = webhookHandler({ "email.bounced": (event) => markBounced(event.data.recipient, event.data.bounce.type), "email.complained": (event) => markComplained(event.data.recipient), "balance.low": (event) => alertOps(`${event.data.emailsLeft} emails left`), }) ``` | Answer | When | | ------ | -------------------------------------------------------------------------- | | `204` | Verified, and its handler finished — or there is none for that type | | `400` | The request fails verification (no detail is given to the sender) | | `405` | Not a `POST` | | `500` | A handler threw, or the secret is missing — Charchy Send retries the event | The secret defaults to `CHARCHY_WEBHOOK_SECRET`; pass `{ secret, onError }` to change it or log refusals. Handlers run before the answer, which must come [within 5 seconds](/docs/webhooks#answer-fast-work-later): keep them short or hand the work to a queue. ## Verify webhooks yourself `verifyWebhook` (also `send.webhooks.verify`) checks the [Standard Webhooks](/docs/webhooks#verify-every-request) signature against the raw body, refuses timestamps more than 5 minutes off, accepts either secret during a rotation, and returns a typed event. It throws `WebhookVerificationError` when the request must be refused — including a body that was already parsed (`express.json()`): pass the raw body. The secret defaults to `CHARCHY_WEBHOOK_SECRET`; it uses Web Crypto, so it runs on the edge too. ```ts // app/api/webhooks/charchy/route.ts import { after } from "next/server" import { verifyWebhook, WebhookVerificationError } from "@charchy/send" export async function POST(request: Request) { try { const event = await verifyWebhook({ payload: await request.text(), headers: request.headers }) after(() => handleCharchyEvent(event)) // answer first, work later return new Response(null, { status: 204 }) } catch (error) { if (error instanceof WebhookVerificationError) return new Response(error.message, { status: 400 }) throw error } } ``` ```ts import express from "express" import { verifyWebhook, type WebhookEvent } from "@charchy/send" // The raw body (a Buffer), not express.json(). app.post("/webhooks/charchy", express.raw({ type: "application/json" }), async (req, res) => { let event: WebhookEvent try { event = await verifyWebhook({ payload: req.body, headers: req.headers }) } catch { return res.status(400).send("Invalid signature") } res.sendStatus(204) await queue.add("charchy-event", event) }) ``` The event is camelCased and discriminated by `type`, so `data` narrows: ```ts switch (event.type) { case "email.bounced": await markBounced(event.data.recipient, event.data.bounce.type) break case "account.paused": await alertOps(`${event.data.code}: ${event.data.reason}`) break } ``` Dedupe by `event.id` and order by `event.createdAt` ([Webhooks](/docs/webhooks)). ## Options ```ts const send = new CharchySend(process.env.CHARCHY_SEND_KEY, { baseUrl: "https://api.charchy.krd", // the default; https only (http just for localhost) maxRetries: 2, // 0–10; 0 turns retries and the automatic key off timeoutMs: 30_000, // per attempt, at most 600 000 fetch: customFetch, // a proxy-aware fetch, or a test double userAgent: "my-app/2.3", // appended to charchy-send-node/ }) ``` The key defaults to `CHARCHY_SEND_KEY` and must be `chy_live_` or `chy_test_` plus 64 hex characters, checked on each request: missing is `missing_api_key`, anything else `invalid_api_key` — local errors, nothing sent, never echoing what you passed. A bad option is a code error and throws at once. Redirects are never followed. With a [test key](/docs/test-mode) nothing is sent or charged and webhooks still fire. ## Help Bugs and feature requests: [GitHub issues](https://github.com/charchyy/charchy-send/issues). Questions about your account: [support@charchy.krd](mailto:support@charchy.krd) — include `error.requestId`. Security reports: [SECURITY.md](https://github.com/charchyy/charchy-send/blob/main/SECURITY.md). --- # Build with AI > A ready prompt for your coding agent per stack, and these docs as Markdown for any AI tool — llms.txt, llms-full.txt and a .md copy of every page. Source: https://charchy.krd/docs/build-with-ai ## Copy a prompt for your agent Pick your stack, copy the prompt, paste it into your coding agent. The agent inspects your project, keeps the key in an environment variable, sends from your server only, puts an idempotency key on every request, sets up a verified webhook endpoint, and is done when a test email to `delivered@sim.charchy.krd` comes back delivered. The Next.js, Convex and Express prompts use the [Node SDK](/docs/sdks/node), [`@charchy/send`](https://www.npmjs.com/package/@charchy/send) (source: [charchyy/charchy-send](https://github.com/charchyy/charchy-send)); Laravel and Django call the API over HTTP. Each prompt points the agent at the matching [guide](/docs/guides/nextjs) where there is one. _(On https://charchy.krd/docs/build-with-ai each stack's prompt has a Copy button. The prompts restate these docs: an agent reading this file already has everything they say.)_ Stack not listed? Any prompt works as a start: the agent reads the full docs from `llms-full.txt` before it writes code. ## These docs as Markdown | Address | What it is | | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | [`/llms.txt`](https://charchy.krd/llms.txt) | A map of the docs: every page, with a link to its Markdown | | [`/llms-full.txt`](https://charchy.krd/llms-full.txt) | Every page in one file, plus the OpenAPI file | | `/docs/.md` | Any page as Markdown — e.g. [`/docs/quickstart.md`](https://charchy.krd/docs/quickstart.md) | | [`/docs/openapi.yaml`](https://charchy.krd/docs/openapi.yaml) | The OpenAPI 3.1 contract | Any docs page requested with `Accept: text/markdown` returns Markdown, so agents never parse HTML. ## On every page Under each page's title: * **Copy page** copies the page as Markdown. * **Open in ChatGPT** and **Open in Claude** start a chat that reads the page first, so answers come from these docs, not from memory. ## Keep your key out of the chat Your agent never needs your API key. The prompts tell it to read `CHARCHY_SEND_KEY` from the environment and never ask you for it — set it yourself, in your `.env` or your host's secret settings. --- # Pricing > Monthly plans from $9, or pay-as-you-go credits at $0.45 per 1,000 emails. Prepaid. Test mode is free. Source: https://charchy.krd/docs/pricing Both ways to pay are **prepaid**. Test mode is always free. ## Monthly plans | Plan | Emails per 30 days | Daily cap | Price | | ----------- | ------------------ | --------- | ------- | | **Starter** | 25,000 | 2,500 | **$9** | | **Growth** | 50,000 | 5,000 | **$16** | | **Pro** | 100,000 | 10,000 | **$32** | | **Scale** | 300,000 | 25,000 | **$90** | * A plan is a **30-day term**, renewed with a payment link. We remind you 7, 3 and 1 days before it ends. * Unused emails **reset** each month — they don't roll over. * Run out mid-month? Sending carries on from your [credits](#pay-as-you-go). * Busy day? A healthy workspace can send up to **twice its daily cap**, paid as usual ([surge allowance](/docs/rate-limits#daily-caps)). * Over 300,000 a month? Write to us for a custom price. ## Pay as you go **$0.45 per 1,000 emails.** Buy credits once, spend them as you send. | Credits | Price | | ----------------------- | ------ | | 25,000 emails (minimum) | $11.25 | | 100,000 emails | $45 | | 500,000 emails | $225 | * Credits last **3 months**. There is one balance with one expiry date, and **every purchase moves the whole balance's expiry to 3 months from that day** — an active sender never loses credits. * We email you 14 and 3 days before credits expire. Expired credits are not refunded. * Credits work with or without a plan. With a plan, its monthly emails are spent first, then credits. A plan is always cheaper for the same emails: $0.30–0.36 per 1,000, against $0.45 for credits. Credits are for low or uneven volume, and for topping up a plan. ## What counts as an email * Each **recipient** counts: one person in `to` and one in `cc` is 2 emails. * You are charged when the email is **accepted**, and refunded when it is canceled, expires, is suppressed, or fails for good. * A **bounced** email counts — it was sent. * **Free:** everything in [test mode](/docs/test-mode), every email to the `@sim.charchy.krd` magic addresses, and emails skipped because every recipient was suppressed. When your plan's emails and your credits are both used up, the API answers [`402 insufficient_balance`](/docs/errors#insufficient_balance). A [`balance.low`](/docs/events#balance.low) webhook warns you when 20% is left since your last top-up, and again at none. ## No free tier Test mode is free and complete — test keys, simulated delivery, real webhooks — so you can build everything before you pay. Charchy Send is invite-only for now. [Request access](/docs/request-access); once approved, you pick a plan or buy credits in your workspace. --- # Request access > Charchy Send is invite-only. Tell us about your app; we answer within a business day. Source: https://charchy.krd/docs/request-access We set up every Charchy Send client by hand. Approved requests get an invitation by email: sign in with that address and your workspace is ready, with a test key and live sending approved. _(The request form is on https://charchy.krd/docs/request-access: name, work email, company, website, what the app sends, emails a month and a note.)_ ## After you send it * **Approved** — an invitation arrives at your work email. It works for 7 days. * **Not a fit** — we email you, with the reason when there is one. Build first if you like: [test mode](/docs/test-mode) is free and complete. Plans and credits are on [Pricing](/docs/pricing). Questions: [support@charchy.krd](mailto:support@charchy.krd). --- # Send an email > POST /v1/emails — every field, what we check, what you get back, and how to read an email's status later. Source: https://charchy.krd/docs/send-email ```http POST https://api.charchy.krd/v1/emails Authorization: Bearer chy_live_… Content-Type: application/json Idempotency-Key: order-confirmation/4821 ``` ```json { "from": "Darin Game ", "to": ["customer@example.com"], "cc": [], "bcc": [], "reply_to": "support@daringaming.com", "subject": "Your order #4821", "html": "

Thanks for your order! …

", "text": "Thanks for your order! …", "headers": { "X-Entity-Ref-ID": "4821" }, "attachments": [ { "filename": "invoice.pdf", "content": "JVBERi0xLjcK…", "content_type": "application/pdf" } ], "tags": { "type": "order_confirmation" }, "scheduled_at": "2026-11-20T09:00:00+03:00", "expires_at": "2026-11-20T12:00:00+03:00" } ``` **Response `200`** ```json { "id": "em_8f2k1x9q4w7m3n5p6r0s2t4v", "status": "queued" } ``` `status` is `scheduled` for a future `scheduled_at`, and `suppressed` when every recipient is on your suppression list. Keep the `id` (`em_` + 24 letters and digits): webhooks and `GET /v1/emails/{id}` use it. ## Fields | Field | Type | Required | Notes | | -------------- | --------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `from` | string | yes | `"Name
"` or a bare address, on one of your workspace's **verified domains**. Any local part works (`orders@`, `no-reply@`). The name may be Kurdish or Arabic, up to 200 characters. | | `to` | string or array | yes | `"customer@example.com"`, `"Name "`, or an array of them. | | `cc`, `bcc` | string or array | no | Same format. `to` + `cc` + `bcc` together: at most **50** addresses, after duplicates are dropped. | | `reply_to` | string or array | no | Where replies go. Up to 5 addresses. | | `subject` | string | yes | Up to 998 characters. Not empty, no line breaks. | | `html` | string | one of the two | Up to 512 KB. | | `text` | string | one of the two | Up to 512 KB. Send only `html` and we make the text part for you. | | `headers` | object | no | Up to 20 custom headers. See [Tags and headers](/docs/tags-and-headers#headers). | | `attachments` | array | no | Up to 3 files, 3 MB together. See [Logos, images and attachments](/docs/images-and-attachments). | | `tags` | object or array | no | Up to 10 pairs — `{ "type": "order" }` or `[{ "name": "type", "value": "order" }]`. They come back in webhooks and filter the log. See [Tags and headers](/docs/tags-and-headers). | | `scheduled_at` | string | no | ISO 8601 with a time zone, up to 30 days ahead. See [Scheduling](/docs/scheduling). | | `expires_at` | string | no | ISO 8601 with a time zone, in the future and after `scheduled_at`. If the email can't leave by then, it is dropped and refunded. See [`expires_at`](/docs/scheduling#expires_at). | * The whole request body may be up to 5 MB. * **Unknown fields are refused** with `validation_error`, so a typo can't drop a field silently. `replyTo` answers *Did you mean "reply\_to"?* * `null` counts as not set, for every optional field. ## What we check In this order, before anything is queued or charged. A failed check answers with its code ([Errors](/docs/errors) has each one). A wrong key always answers first — never a body error. 1. **Your key** — present (`missing_api_key`), a real key that isn't revoked (`invalid_api_key`). 2. **The body** — valid JSON (`invalid_json`), valid fields (`validation_error`, with the `field` named), size (`payload_too_large`), recipients (`too_many_recipients`), attachments (`invalid_attachment`), schedule (`schedule_out_of_range`), the `Idempotency-Key` header (`invalid_idempotency_key`). 3. **Rate limit** — 10 requests a second per workspace, bursts of 20 (`rate_limit_exceeded`). 4. **Idempotency** — the same key seen before (`idempotency_conflict`, `idempotency_in_flight`). 5. **The key's domain lock** — a key locked to one domain sends only from it (`restricted_api_key`). 6. **Live keys only:** sending not paused (`sending_paused`), and `from` on a verified domain of this workspace (`sender_not_allowed`, `domain_not_verified`). 7. **Approval** — before your workspace is approved, a live key sends only to your team's own addresses (`not_approved`). 8. **Sending available** — live sending not halted on our side (`sending_unavailable`). 9. **Daily caps** — under your rolling-day cap, or the test allowance (`daily_limit_reached`). 10. **Balance** — emails left to spend (`insufficient_balance`). Only approved live sends are charged. ## Addresses * Kurdish and Arabic **display names** work everywhere: `"دارین گەیم "`. We encode them for you. * **International domains** (`user@مثال.com`) are converted to their ASCII form for you. * **Non-ASCII local parts** (`ئاراس@example.com`) are refused with `validation_error`: too many receiving servers still can't take them. * A line break (CR or LF) in any address, subject or header is refused with `validation_error` (it is how header injection works). * Addresses are stored in lowercase. The same address twice (in `to` and `cc`, say) gets one copy. ## Reserved headers We set these, so `headers` can't: `From`, `To`, `Cc`, `Bcc`, `Subject`, `Reply-To`, `Sender`, `Date`, `Return-Path`, `Message-ID`, `MIME-Version`, `Content-*`, `DKIM-*`, `X-SES-*`. Setting one returns `validation_error`. Everything else, including `List-Unsubscribe`, is yours — see [Tags and headers](/docs/tags-and-headers#headers). ## Suppressed addresses An address that **hard-bounced** or **marked your mail as spam** goes on your workspace's suppression list, and we don't send to it again — this protects your domain's reputation. * An address that only **unsubscribed** from your newsletters is *not* skipped: people who leave your newsletter still need their password reset. * A suppressed recipient is skipped and not charged; the other recipients get the email as usual. Each skipped recipient gets a `suppressed` event and its own `email.suppressed` webhook. * If every recipient is suppressed, the request still succeeds with status `suppressed`, and nothing is charged. * The list is under **Suppressions** in the dashboard, where you can let a bounced address back — see [Suppressions](/docs/suppressions). ## Statuses ``` scheduled → queued → sending → sent → delivered ↘ delivery_delayed ↘ bounced ↘ complained side exits: canceled · expired · suppressed · failed · unknown ``` | Status | Means | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `scheduled` | Waiting for its `scheduled_at`. | | `queued` | Accepted and waiting its turn. | | `sending` | Being handed to our delivery infrastructure. | | `sent` | Our infrastructure accepted it. | | `delivered` | The recipient's mail server accepted it. | | `delivery_delayed` | The receiving server is slow or refusing for now; delivery keeps being tried. | | `bounced` | The receiving server refused it. A hard bounce (`bounce.type` `permanent`) also suppresses the address; a temporary one, like a full mailbox, doesn't. | | `complained` | The recipient marked it as spam. The address is suppressed. | | `canceled` | You canceled it before it left. Refunded. | | `expired` | It couldn't leave in time: its `expires_at` passed, or it was held 3 days past its due time while sending was paused. Refunded. | | `suppressed` | Every recipient was on the suppression list. Not charged. | | `failed` | It couldn't be sent — for example because your domain stopped verifying, or temporary errors went on until the retries ran out. Refunded. | | `unknown` | We got no answer from the delivery side and no event for 30 minutes after it was handed over. See below. | An `expired`, `failed` or `unknown` event has a `reason` saying why, such as `expires_at`, `held_too_long`, `domain_not_verified` or `retries_exhausted`. ### Emails with several recipients An email to several people has one status, taken from its recipients in this order: 1. any recipient complained → `complained`; 2. else any recipient bounced → `bounced`; 3. else every recipient was delivered → `delivered`; 4. else any recipient is delayed → `delivery_delayed`; 5. else → `sent`. Suppressed recipients never left, so they don't count. Each recipient's events are on the timeline with a `recipient` field and send their own webhook — an email to three people where one bounces reads `bounced`, and the timeline still shows the other two delivered. See [Webhooks](/docs/webhooks) and [Events reference](/docs/events). ### `unknown` If a send times out on our side, the email may already have left, so we never resend it. It stays `sending` until a delivery event settles it, and shows `unknown` after 30 minutes without one. The charge stays. A later event still moves it on to `sent`, `delivered` and so on. ## Read an email Needs a key with **full** permission. ```ts import { CharchySend } from "@charchy/send" const send = new CharchySend() // reads CHARCHY_SEND_KEY const { data, error } = await send.emails.get("em_8f2k1x9q4w7m3n5p6r0s2t4v") ``` ```bash curl https://api.charchy.krd/v1/emails/em_8f2k1x9q4w7m3n5p6r0s2t4v \ -H "Authorization: Bearer $CHARCHY_SEND_KEY" ``` ```json { "id": "em_8f2k1x9q4w7m3n5p6r0s2t4v", "status": "delivered", "from": "Darin Game ", "to": ["customer@example.com"], "cc": [], "bcc": [], "reply_to": ["support@daringaming.com"], "subject": "Your order #4821", "tags": { "type": "order_confirmation" }, "test": false, "created_at": "2026-11-16T09:00:00.120Z", "scheduled_at": null, "expires_at": null, "events": [ { "type": "queued", "at": "2026-11-16T09:00:00.120Z" }, { "type": "sent", "at": "2026-11-16T09:00:00.910Z" }, { "type": "delivered", "at": "2026-11-16T09:00:02.400Z", "recipient": "customer@example.com" } ] } ``` Events on a test email carry `"simulated": true`. A bounce event carries `bounce` (`type`, `sub_type`, `diagnostic_code`). Emails and their events are kept for **30 days**; their content for **7 days** after the email was due. ## List emails Needs a key with **full** permission. ```ts const { data, error } = await send.emails.list({ limit: 20, status: "bounced" }) ``` ```bash curl "https://api.charchy.krd/v1/emails?limit=20&status=bounced" \ -H "Authorization: Bearer $CHARCHY_SEND_KEY" ``` | Query | Notes | | -------- | -------------------------------------------------------------- | | `limit` | 1–100, default 20. Newest first. | | `after` | The `next_cursor` of the previous page, with the same filters. | | `status` | One status from the table above. | | `tag` | `key:value`, e.g. `type:order_confirmation`. | | `to` | A recipient address. | ```json { "data": [ { "id": "em_8f2k1x9q4w7m3n5p6r0s2t4v", "status": "bounced", "from": "Darin Game ", "to": ["old@example.com"], "subject": "Your order #4821", "tags": { "type": "order_confirmation" }, "test": false, "created_at": "2026-11-16T09:00:00.120Z", "scheduled_at": null } ], "has_more": true, "next_cursor": "…" } ``` * `next_cursor` is only there when `has_more` is `true`. Treat it as opaque. * `tag` and `to` filter each page after it is read, so a page can hold fewer than `limit` emails — even none — while `has_more` is `true`. Keep following `next_cursor`. * The list covers the last 30 days. ## Permissions A **sending** key can send and read [`GET /v1/usage`](/docs/rate-limits#check-where-you-stand). Reading, listing, rescheduling and canceling emails need a **full** key (`restricted_api_key` otherwise). --- # Batch > POST /v1/emails/batch — up to 100 emails in one request, checked all-or-nothing. Source: https://charchy.krd/docs/batch Up to **100 emails** in one request — a nightly digest of account alerts, receipts for a bulk import. Each has its own recipients, subject, body, tags and `scheduled_at`. ```http POST https://api.charchy.krd/v1/emails/batch Authorization: Bearer chy_live_… Content-Type: application/json Idempotency-Key: november-invoices/2026-11 ``` ```json { "emails": [ { "from": "Darin Game ", "to": ["ara@example.com"], "subject": "Your November invoice", "html": "

Hi Ara, your invoice is ready…

", "tags": { "type": "invoice" } }, { "from": "Darin Game ", "to": ["shilan@example.com"], "subject": "Your November invoice", "html": "

Hi Shilan, your invoice is ready…

", "tags": { "type": "invoice" }, "scheduled_at": "2026-11-17T08:00:00+03:00" } ] } ``` A bare array, without the `emails` wrapper, works too. **Response `200`** — the ids in the order you sent them: ```json { "emails": [ { "id": "em_3n8v2c7x1k5d9q4w7m2r6t1y", "status": "queued" }, { "id": "em_9q4w7m2r6t1y3n8v2c7x1k5d", "status": "scheduled" } ] } ``` ## Rules * **Same fields** as [Send an email](/docs/send-email), per email. * **No attachments** in a batch (`validation_error`) — send those one by one. * **All or nothing.** If any email is invalid, nothing is sent: you get `422` with every problem by the email's index, each item with its own `code` and a `field` naming the email: ```json { "error": { "code": "validation_error", "message": "2 of the emails are invalid, so none were sent.", "docs": "https://charchy.krd/docs/errors#validation_error", "items": [ { "index": 0, "code": "validation_error", "field": "emails[0].to", "message": "\"ara@\" is not an email address." }, { "index": 7, "code": "schedule_out_of_range", "field": "emails[7].scheduled_at", "message": "scheduled_at is more than 30 days ahead." } ] } } ``` We never answer `200` while some emails failed — a partial success is too easy to miss in your logs. * A problem with the batch itself — an empty list, more than 100 emails, a field other than `emails` — answers `400 validation_error`. * The workspace checks (`from` domain, approval, caps, balance) run on the whole batch: the first email that fails refuses the batch with that one error, its `field` naming the email (`emails[3].from`). * A suppressed recipient is skipped, as in a single send; it doesn't fail the batch. * **One charge** for the whole batch, counted per recipient like single sends. * **One idempotency key** covers the whole batch: a retry with the same key returns the same ids and sends nothing twice. * A batch counts as **one request** against the rate limit of 10 a second. ## When to use it Batch saves requests, not delivery time: queued emails go out at the same pace either way. Use it when you already have many emails in hand; for one email per user action, a single `POST /v1/emails` is simpler. --- # Scheduling and expiry > Send later with scheduled_at, change or cancel it before it leaves, and let time-sensitive emails expire with expires_at. Source: https://charchy.krd/docs/scheduling ## `scheduled_at` Send later — a booking reminder the day before, a receipt at the start of business hours. ```json { "from": "Clinic ", "to": ["patient@example.com"], "subject": "Reminder: your appointment tomorrow at 10:00", "text": "…", "scheduled_at": "2026-11-20T09:00:00+03:00" } ``` ```json { "id": "em_5k2m8x1q9w3r7v4n6p0t2c8d", "status": "scheduled" } ``` * ISO 8601 with a time zone (`+03:00` is Iraq time, `Z` is UTC). Without one, `validation_error` — it would mean a different moment on every server. * Up to **30 days** ahead. Further returns `422 schedule_out_of_range`. * A time in the past means *now*: the email is `queued`, not `scheduled`. * Charged when you send the request; the charge stands even if your credits expire before it goes out. ### Change the time While the email is still `scheduled` (a key with **full** permission): ```ts import { CharchySend } from "@charchy/send" const send = new CharchySend() // reads CHARCHY_SEND_KEY const { data, error } = await send.emails.update("em_5k2m8x1q9w3r7v4n6p0t2c8d", { scheduledAt: "2026-11-20T08:00:00+03:00", }) ``` ```bash curl -X PATCH https://api.charchy.krd/v1/emails/em_5k2m8x1q9w3r7v4n6p0t2c8d \ -H "Authorization: Bearer $CHARCHY_SEND_KEY" \ -H "Content-Type: application/json" \ -d '{ "scheduled_at": "2026-11-20T08:00:00+03:00" }' ``` ```json { "id": "em_5k2m8x1q9w3r7v4n6p0t2c8d", "status": "scheduled", "scheduled_at": "2026-11-20T05:00:00.000Z" } ``` * Same rules as `scheduled_at` above; a past time sends it at once. * The new time must be before the email's `expires_at`, if it has one. * Only `scheduled_at` can change, and not once the email is `queued` or later (`validation_error`). ### Cancel While the email is `scheduled` or `queued` (a key with **full** permission): ```ts const { data, error } = await send.emails.cancel("em_5k2m8x1q9w3r7v4n6p0t2c8d") ``` ```bash curl -X POST https://api.charchy.krd/v1/emails/em_5k2m8x1q9w3r7v4n6p0t2c8d/cancel \ -H "Authorization: Bearer $CHARCHY_SEND_KEY" ``` ```json { "id": "em_5k2m8x1q9w3r7v4n6p0t2c8d", "status": "canceled" } ``` A canceled email is refunded and fires `email.canceled`; canceling again answers the same. Once `sending` or later, it can't be canceled (`validation_error`). Refunds go back where the charge came from: plan emails to their plan term while it runs, credits to your balance while it hasn't expired. Past either, there is nothing to give back. ## `expires_at` If the email can't leave by `expires_at` — a long queue, sending paused or held — we drop it instead of sending it late. A sign-in code that arrives 20 minutes after the person gave up is worse than none: they already asked for a new one, and now they have two. ```json { "from": "My App ", "to": ["user@example.com"], "subject": "Your sign-in code: 482910", "text": "Your code is 482910. It expires in 10 minutes.", "expires_at": "2026-11-16T12:10:00Z" } ``` * Must be in the future, and after `scheduled_at` if set; otherwise `validation_error`. * A dropped email gets status `expired` (`reason` `expires_at`), an `email.expired` webhook, and is **refunded**. * Retries after a temporary failure never go past `expires_at`: if the next try would land after it, the email ends as `failed` (`retries_exhausted`) and is refunded. * It is about *leaving* our system, not reaching the inbox: once sent, the email is the receiving server's. * Match it to the code's lifetime: a 10-minute code gets an `expires_at` 10 minutes from now. * Queued emails with `expires_at` leave first, soonest to expire first, so a code never waits behind your receipts. Together, `scheduled_at` is the earliest an email may leave and `expires_at` the latest. ## Held mail When live sending is paused for your workspace — by our [automatic pauses](/docs/rate-limits#automatic-pauses), by a person, or by our delivery provider — or held on our side, live mail you already sent us is **held**, not failed: it keeps its place and goes out when sending resumes. It ends early only when: * its `expires_at` passes — `expired`, `reason` `expires_at`, refunded; or * it has waited **3 days** past its due time (its `scheduled_at`, or when you sent it) — `expired`, `reason` `held_too_long`, refunded. Transactional mail days late is worse than none. Test mail and magic addresses are never held. --- # Idempotency > Send an Idempotency-Key on every request, so a retry never sends an email twice. Source: https://charchy.krd/docs/idempotency A network failure after we accepted your email but before your server read the answer makes your code retry — and the customer gets two receipts. An `Idempotency-Key` header prevents it. **Send one on every request.** ```http POST /v1/emails Idempotency-Key: password-reset/7f1c2a ``` ## How it works | You send | You get | | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | A new key | The email is accepted as usual. | | The same key and the **same body**, again | The first answer again, the same ids. No second email, no second charge. | | The same key and a **different body** | `409 idempotency_conflict`. Nothing is sent. | | The same key while the first request is **still running** | `409 idempotency_in_flight`. Wait the `Retry-After` seconds and retry. | | The same key after the first request was **refused** | Checked again from the start, as a new request. | | An empty key, one over 256 characters, or one with anything but printable ASCII | `400 invalid_idempotency_key`. Nothing is sent. | * A key is 1–256 printable ASCII characters: no line breaks, tabs, or Kurdish and Arabic letters. * "Same body" means the same JSON values: key order and spacing don't matter; any changed value does. * **Only accepted requests are remembered.** A refused request — no balance, over a cap, a domain not verified — leaves the key free, so you can fix the cause and retry with the same key. * Keys are kept **24 hours** from the first request, then the same key is new again. They are per workspace: two workspaces never collide. * One key covers a whole [batch](/docs/batch). `POST /v1/emails` and `POST /v1/emails/batch` share keys, so reusing a key on the other endpoint is a conflict. * `idempotency_in_flight` only happens while a request with attachments or a large body is uploading; any other copy waits for the first and gets its answer. ## Choosing a key Build the key from **the event that causes the email**, not the moment you send it — a random key made inside your retry loop is new every time and protects nothing. A format that works everywhere: **`/`**. | Email | A good key | | ------------------ | --------------------------------- | | Welcome email | `welcome-user/123` | | Order confirmation | `order-confirmation/4821` | | Password reset | `password-reset/` | | Sign-in code | `signin-code/` | | Monthly invoice | `invoice//2026-11` | From a job queue, the job's id is a good key — a retried job keeps its id. ## Retrying safely With a key on every request, this policy is safe: | Answer | Retry? | | ------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | Network error or timeout | Yes, with the **same key**. | | `500 internal_error` | Yes, with backoff. | | `429 rate_limit_exceeded`, `429 daily_limit_reached`, `503 sending_unavailable` | Yes, after the `Retry-After` header's seconds. | | `409 idempotency_in_flight` | Yes, after the `Retry-After` header's seconds. | | `402 insufficient_balance` | **No.** Add credits first, then send again — the same key works. | | Any other `4xx` | **No.** The request itself is wrong; fix it. | ```ts // Node / TypeScript: a send with retries that can never duplicate. async function sendEmail(email: object, idempotencyKey: string) { for (let attempt = 1; ; attempt++) { let response: Response | undefined try { response = await fetch("https://api.charchy.krd/v1/emails", { method: "POST", headers: { Authorization: `Bearer ${process.env.CHARCHY_SEND_KEY}`, "Content-Type": "application/json", "Idempotency-Key": idempotencyKey, }, body: JSON.stringify(email), }) } catch { // network error: retry below } if (response?.ok) return response.json() // { id, status } const code = response ? (await response.json()).error?.code : "network_error" const retryable = !response || response.status >= 500 || response.status === 429 || code === "idempotency_in_flight" if (!retryable || attempt === 5) throw new Error(`Charchy Send: ${code}`) const retryAfter = Number(response?.headers.get("retry-after")) || 2 ** attempt await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000)) } } ``` --- # Logos, images and attachments > Three ways to put a logo, an image or a file in an email — hosted images, inline images and attachments — and when to use each. Source: https://charchy.krd/docs/images-and-attachments | Way | Best for | How | | ------------------------------------------------ | --------------------------------------------------------------- | ------------------------------------------------------------------------- | | [**Hosted image**](#hosted-images) (recommended) | Logos, headers, product photos | `` in your `html` | | [**Inline image**](#inline-images) | A logo that must show even when the reader blocks remote images | An attachment with a `content_id`, and `` in your `html` | | [**Attachment**](#attachments) | Invoices, receipts, tickets | `attachments: [{ filename, content, content_type }]` | ## Hosted images A link to a file on the web: the email stays small, delivers better and loads faster. **Use this for logos.** Upload once — on **Developers → Images** in the dashboard, or with the API (a **full** key) — and use the URL in every email: ```ts import { readFile } from "node:fs/promises" import { CharchySend } from "@charchy/send" const send = new CharchySend() // reads CHARCHY_SEND_KEY const { data, error } = await send.images.upload(await readFile("logo.png"), { filename: "logo.png" }) ``` ```bash curl https://api.charchy.krd/v1/images \ -H "Authorization: Bearer $CHARCHY_SEND_KEY" \ -F "file=@logo.png" ``` ```json { "id": "img_4t8w2k6m1q9v3n7p5r0s2x8c", "url": "https://files.charchy.krd/i/4t8w2k6m1q9v3n7p5r0s2x8c/logo.png", "content_type": "image/png", "size": 18342 } ``` ```html Darin Game ``` * PNG, JPEG, GIF or WebP, up to **2 MB** each, **200** per workspace. The type is judged by the file's content, not its name: an SVG, or a file that only calls itself `image/png`, is refused. (**No SVG**: Gmail and Outlook don't show it.) * Send the file as `multipart/form-data` in a field named `file`. * Over 2 MB answers `413 payload_too_large`; not an image, or a 201st image, `400 validation_error`. * The URL is public and never changes. Images are never deleted by age — they live in emails people open months later. * **Delete** an image on the **Images** page (API uploads are listed there too) to make room once you have 200. Its URL stops working at once, so sent emails show a broken image. Deleting your workspace deletes them all. * Any other `https://` image URL works too. Always set `alt`, `width` and `height`: many readers see the email before images load, or never load them. ## Inline images An inline image travels inside the email, so it shows even when remote images are blocked — but its size is added to **every** email. Attach it with a `content_id` and point an `` at `cid:` plus that id: ```json { "from": "Darin Game ", "to": ["customer@example.com"], "subject": "Your order #4821", "html": "\"Darin

Thanks for your order!

", "attachments": [ { "filename": "logo.png", "content": "iVBORw0KGgoAAAANSUhEUgAA…", "content_type": "image/png", "content_id": "logo" } ] } ``` An inline image counts toward the attachment limits below. ## Attachments ```json { "attachments": [ { "filename": "invoice-4821.pdf", "content": "JVBERi0xLjcKJeLjz9MK…", "content_type": "application/pdf" } ] } ``` | Field | Notes | | -------------- | -------------------------------------------------------------------------------------------------------------- | | `filename` | Required. What the reader sees: a plain file name, no folders, up to 255 characters. | | `content` | Required. The file, base64-encoded. Line breaks in it are fine. | | `content_type` | Required. e.g. `application/pdf`, `image/png`. | | `content_id` | Only for [inline images](#inline-images): 1–100 letters, digits, `.`, `_`, `@` or `-`, different on each file. | * Up to **3 files**, **3 MB** together (before base64). A PDF invoice is usually 50–500 KB; bigger files belong behind a download link. * Base64 adds about a third, so keep the whole request under the **5 MB** body limit. * Executable and script types (`.exe`, `.bat`, `.js`, `.vbs` and similar) and empty files are refused with `invalid_attachment`. * No attachments in a [batch](/docs/batch). * Files are deleted from our storage once the email is sent; the log keeps only their names. ```ts import { readFile } from "node:fs/promises" const invoice = await readFile("invoice-4821.pdf") const attachment = { filename: "invoice-4821.pdf", content: invoice.toString("base64"), content_type: "application/pdf", } ``` --- # Tags and headers > Label emails with tags to find them and route their webhooks, and add your own email headers. Source: https://charchy.krd/docs/tags-and-headers ## Tags Tags come back in every [webhook](/docs/webhooks) for the email, and filter the log — in the dashboard and with `GET /v1/emails?tag=type:invoice`. Send them as an object: ```json { "tags": { "type": "order_confirmation", "store": "erbil" } } ``` or as an array of name/value pairs: ```json { "tags": [{ "name": "type", "value": "order_confirmation" }, { "name": "store", "value": "erbil" }] } ``` Either way they come back as an object. * Up to **10** tags per email, each name once. * Names and values use letters, digits, `_` and `-` only, up to 256 characters each. * A few names are reserved for our own use and refused: `category`, `workspaceId`, `apiEmailId`, `emailSendId`, `outboundEmailId` (in any case). * Tags are labels, not data: an order id is fine, personal details are not. ### Good uses | Tag | Why | | ---------------------- | ------------------------------------------------------------------- | | `type: password_reset` | See bounce rates per kind of email; route webhooks in your handler. | | `user_id: 1842` | Find every email a customer got. | | `env: staging` | Tell environments apart in one workspace. | ## Headers ```json { "headers": { "X-Entity-Ref-ID": "order-4821", "List-Unsubscribe": "", "List-Unsubscribe-Post": "List-Unsubscribe=One-Click" } } ``` * Up to **20** headers per email, each name once (in any case). * Names are printable ASCII without a colon, up to 76 characters. Values are ASCII, up to 998 characters, with no line breaks — encode anything else (RFC 2047) first. * `X-Entity-Ref-ID` with a unique value stops Gmail from threading separate emails (such as two sign-in codes) into one conversation. * **`List-Unsubscribe`** and **`List-Unsubscribe-Post`** (one-click unsubscribe, RFC 8058) are allowed — right for product notices a person can switch off, like a weekly activity summary. Your URL must turn the notice off when it receives the POST. A workspace where most emails carry these headers looks like a mailing list ([how we check](/docs/transactional#how-we-check)). * **Reserved** (we set them): `From`, `To`, `Cc`, `Bcc`, `Subject`, `Reply-To`, `Sender`, `Date`, `Return-Path`, `Message-ID`, `MIME-Version`, `Content-*`, `DKIM-*`, `X-SES-*`. Setting one answers `validation_error`; use the request's own fields (`from`, `to`, `reply_to`, …) instead. --- # Test mode > Test keys and the @sim.charchy.krd magic addresses — build, test and run CI without sending a real email or spending a credit. Source: https://charchy.krd/docs/test-mode Test mode is free and is the real API — same validation, answers and webhooks — except nothing reaches a real inbox. ## Test keys Test keys start with `chy_test_`. Your welcome screen has one ready; make more under **API keys**. Use them in development, staging and CI. A test key: * goes through the same **authentication, validation, idempotency and rate limit** as a live key, with the same codes; * may use **any domain** in `from`, and skips the checks that only matter for real mail: domain verification, approval, pauses and your balance — so it keeps working while live sending is paused; * **never sends**. The email turns `sent`, and a second later every recipient that isn't a [magic address](#magic-addresses) gets a simulated `delivered`. Its timeline events carry `"simulated": true`, and **your webhooks fire for real** — one per recipient event, the same payload as live mail — so you can test your endpoint end to end; * still skips addresses on your suppression list; * shows its emails in **Emails**, marked as test (`"test": true` in the API and in every webhook's `data`); * is **free**: it never touches your plan's emails, credits or daily cap. Test sends have their own allowance of 1,000 recipients in a rolling 24 hours per workspace, shared with magic addresses; past it, `429 daily_limit_reached`. `GET /v1/usage` shows how many you've used. ## Magic addresses Send to these for a known outcome. They work with **test and live keys**, never reach a real mail server, and are free: even with a live key they never count against your daily cap or balance — only against the 1,000-a-day test allowance. | Address | What happens | Webhooks | | ---------------------------- | ------------------------------------------------------- | --------------------------------------------------------- | | `delivered@sim.charchy.krd` | Delivered | `email.sent`, `email.delivered` | | `bounced@sim.charchy.krd` | Hard bounce (`permanent`) | `email.sent`, `email.bounced` | | `complained@sim.charchy.krd` | Delivered, then marked as spam | `email.sent`, `email.delivered`, `email.complained` | | `suppressed@sim.charchy.krd` | Skipped as suppressed when the request is accepted | `email.suppressed` | | `delayed@sim.charchy.krd` | Delivery delayed, then delivered about 10 seconds later | `email.sent`, `email.delivery_delayed`, `email.delivered` | * Events arrive about a second after the email turns `sent`. * Add a `+label` to tell tests apart: `delivered+signup@sim.charchy.krd`, `bounced+invoice-test@sim.charchy.krd`. * With a live key, the rest of the request is still checked as live: `from` must be on a verified domain, and a paused workspace answers `sending_paused`. * `sim.charchy.krd` has no mail server, so nothing sent to it can be accepted by anyone, even by mistake. A simulated bounce or complaint never touches your real suppression list, bounce rate or usage, and never pauses your sending. ## A CI check in one request Fails the build if the email is refused. [Testing in CI](/docs/guides/testing-in-ci) goes further. ```bash curl --fail-with-body https://api.charchy.krd/v1/emails \ -H "Authorization: Bearer $CHARCHY_SEND_TEST_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: ci-$GITHUB_RUN_ID" \ -d '{ "from": "CI ", "to": ["delivered+ci@sim.charchy.krd"], "subject": "CI smoke test", "text": "ok" }' ``` ## Before you are approved: your own inbox Until your workspace is approved for sending, a live key sends real email only to **your team's own addresses** (the people in your workspace), up to **50 recipients in a rolling 24 hours**, free. Any other recipient answers `403 not_approved`. Magic addresses work throughout. --- # Domains and DNS > Verify your sending domain with three DKIM records and a DMARC record — or one click with Cloudflare — and avoid the two classic DNS mistakes. Source: https://charchy.krd/docs/domains Every email leaves from **your own domain**, DKIM-signed with your domain's key. Receiving servers check that signature against your DNS. ## Add a domain 1. In the dashboard, open **Domains** and add the domain you send from, e.g. `daringaming.com` (or a subdomain such as `mail.daringaming.com`). 2. Publish the records we show you: * **Three `CNAME` records** for DKIM, named like `._domainkey.daringaming.com`. * A **DMARC** `TXT` record at `_dmarc.daringaming.com`, if you don't have one. 3. The page checks your DNS live and turns **Verified** when it sees them — usually within minutes, at most a few hours. Once verified, send from **any address** on the domain (`orders@`, `no-reply@`, `support@`) without confirming each one. ### Add with Cloudflare or Vercel If your DNS is on Cloudflare, press **Add with Cloudflare**, sign in, and approve the records. Cloudflare creates them for you. When the button shows **Add with Vercel** for a domain on Vercel's nameservers, it does the same there. ### Step by step for your DNS provider [Cloudflare](/docs/domains/cloudflare) · [Hostinger](/docs/domains/hostinger) · [GoDaddy](/docs/domains/godaddy) · [Namecheap](/docs/domains/namecheap) · [Route 53](/docs/domains/route-53) · [Vercel](/docs/domains/vercel) ## The DMARC record DMARC tells receiving servers what to do with mail that fails its checks; Gmail and Yahoo expect one from every sender. Start with a report-only policy: ``` _dmarc.daringaming.com TXT "v=DMARC1; p=none; rua=mailto:dmarc@daringaming.com" ``` After a few weeks of good delivery, move to `p=quarantine`, then `p=reject` ([why](/docs/deliverability)). ## The two classic DNS mistakes ### 1. The domain written twice Many DNS panels append your domain to every name. Paste the full name and the record ends up at ``` abc123._domainkey.daringaming.com.daringaming.com ``` and never verifies. Enter only the part **before** your domain: `abc123._domainkey`. ### 2. The Cloudflare proxy on a DKIM record A **Proxied** (orange cloud) `CNAME` on Cloudflare hides its target, so DKIM can't be checked. Set all three DKIM records to **DNS only** (grey cloud). **Add with Cloudflare** does this for you. ## Keys and domains * A **live key** can be locked to one domain at creation; sending from another domain gets `403 restricted_api_key`. * A `from` on a domain not verified in your workspace gets `403 domain_not_verified`, or `403 sender_not_allowed` if your workspace can't use the domain. * [Test keys](/docs/test-mode) can use any domain. * Up to **10 domains** per workspace. ## If a domain stops verifying We re-check every verified domain daily. If its DKIM records are gone (DNS edited, domain moved to another provider) at two checks a few hours apart — one DNS hiccup changes nothing — it becomes **unverified**: * new emails from it get `403 domain_not_verified`; * scheduled emails from it fail when their time comes, are refunded, and fire `email.failed`; * queued emails from it fail the same way; * your owners and admins get an email and a notification, and you get a `domain.failed` webhook. Put the same records back: we check again every few hours and turn the domain back on by ourselves, with a `domain.verified` webhook. **Check records** on the Domains page brings that check forward. If it hasn't recovered within a day of the records being back, start verification again for new records. --- # Cloudflare > Add Charchy Send's DNS records on Cloudflare — in one click with Add with Cloudflare, or by hand. Source: https://charchy.krd/docs/domains/cloudflare ## Add with Cloudflare (recommended) 1. In Charchy, open **Domains**, add your domain, and press **Add with Cloudflare**. 2. Sign in to Cloudflare and pick the account that holds the domain. 3. Approve the records. Cloudflare creates them, set to **DNS only**. The Domains page turns **Verified** once Cloudflare serves the records — usually within minutes. ## By hand Open your domain in the Cloudflare dashboard, then **DNS → Records → Add record** for each record Charchy shows: | Field | Value | | ------------ | ----------------------------------------------------------------------------------------- | | Type | `CNAME` | | Name | The part before your domain, e.g. `abc123._domainkey` (Cloudflare adds the domain itself) | | Target | The value from Charchy, copied with its copy button | | Proxy status | **DNS only** (grey cloud) — never Proxied | | TTL | Auto | Repeat for all three DKIM records. If Charchy shows a DMARC record, add it as `TXT`, name `_dmarc`, with the value shown. A **Proxied** CNAME hides its target, so the DKIM check fails. Click an orange cloud to switch it to **DNS only**. --- # Hostinger > Add Charchy Send's DNS records in Hostinger's hPanel. Source: https://charchy.krd/docs/domains/hostinger For domains whose nameservers point to Hostinger. If they point elsewhere, add the records there. 1. In **hPanel**, open **Domains**, then your domain's **DNS / Nameservers** page (the list of **DNS records**). 2. For each DKIM record Charchy shows, add a record: | Field | Value | | ------ | ---------------------------------------------------------- | | Type | `CNAME` | | Name | Only the part before your domain, e.g. `abc123._domainkey` | | Target | The value from Charchy | | TTL | Leave the default | 3. If Charchy shows a DMARC record and you don't have one yet, add type `TXT`, name `_dmarc`, with the value shown. Hostinger appends your domain to every name, so a full name pasted in **Name** ends up written twice — the most common reason a domain won't verify ([Troubleshooting](/docs/troubleshooting#my-domain-wont-verify)). --- # GoDaddy > Add Charchy Send's DNS records in GoDaddy's DNS management. Source: https://charchy.krd/docs/domains/godaddy For domains on GoDaddy's nameservers. If the DNS is hosted elsewhere, add the records there. 1. Sign in to GoDaddy, open your domain portfolio, choose the domain, and open its **DNS** page. 2. **Add New Record** for each DKIM record Charchy shows: | Field | Value | | ----- | ---------------------------------------------------------- | | Type | `CNAME` | | Name | Only the part before your domain, e.g. `abc123._domainkey` | | Value | The value from Charchy | | TTL | Leave the default | 3. If Charchy shows a DMARC record, add type `TXT`, name `_dmarc`, with the value shown. If a `_dmarc` record already exists, keep it — you need only one. GoDaddy adds your domain to every name: enter `abc123._domainkey`, not the full name. --- # Namecheap > Add Charchy Send's DNS records in Namecheap's Advanced DNS. Source: https://charchy.krd/docs/domains/namecheap For domains on Namecheap's own DNS (BasicDNS or PremiumDNS). If the nameservers point elsewhere, add the records there. 1. Sign in to Namecheap, open **Domain List**, and press **Manage** next to the domain. 2. Open the **Advanced DNS** tab and, under **Host Records**, **Add New Record** for each DKIM record Charchy shows: | Field | Value | | ----- | ---------------------------------------------------------- | | Type | `CNAME Record` | | Host | Only the part before your domain, e.g. `abc123._domainkey` | | Value | The value from Charchy | | TTL | Automatic | 3. Save each record with the check mark. 4. If Charchy shows a DMARC record and you don't have one, add a `TXT Record` with host `_dmarc` and the value shown. Namecheap appends your domain to the **Host**: enter `abc123._domainkey`, not the full name. --- # Route 53 > Add Charchy Send's DNS records in an Amazon Route 53 hosted zone. Source: https://charchy.krd/docs/domains/route-53 1. In the Route 53 console, open **Hosted zones** and choose your domain's public hosted zone. 2. **Create record** for each DKIM record Charchy shows: | Field | Value | | -------------- | -------------------------------------------------------------------------------------------------------- | | Record name | Only the part before your domain, e.g. `abc123._domainkey` — the console shows your domain after the box | | Record type | `CNAME` | | Value | The value from Charchy | | TTL | 300 (or the default) | | Routing policy | Simple routing | 3. If Charchy shows a DMARC record and you don't have one, create a `TXT` record named `_dmarc`. Route 53 wants TXT values **in double quotes**: ``` "v=DMARC1; p=none; rua=mailto:dmarc@yourdomain.com" ``` Edit the **public** hosted zone your domain's nameservers point to — a private zone or a leftover old zone is never queried. --- # Vercel > Add Charchy Send's DNS records in Vercel DNS — in the dashboard or with the Vercel CLI. Source: https://charchy.krd/docs/domains/vercel For domains on **Vercel's nameservers** (`ns1.vercel-dns.com`, `ns2.vercel-dns.com`). Records added in Vercel do nothing while the domain's nameservers point elsewhere — check with `dig NS yourdomain.com +short`, and if the answer isn't Vercel's, add the records at that provider instead. When the Domains page in Charchy shows **Add with Vercel**, it does all of this in one step. ## In the dashboard 1. In Vercel, open **Domains** in your team's sidebar and choose the domain. 2. Add a record for each DKIM record Charchy shows: | Field | Value | | ----- | --------------------------------------------------------------------------------------------------- | | Name | Only the part before your domain, e.g. `abc123._domainkey` — not `abc123._domainkey.yourdomain.com` | | Type | `CNAME` | | Value | The value from Charchy | | TTL | Leave the default (60) | 3. If Charchy shows a DMARC record and you don't have one, add type `TXT`, name `_dmarc`, with the value shown. ## With the Vercel CLI ```bash # once per DKIM record, with the name and value from your Domains page vercel dns add yourdomain.com abc123._domainkey CNAME # DMARC, if you don't have one vercel dns add yourdomain.com _dmarc TXT "v=DMARC1; p=none; rua=mailto:dmarc@yourdomain.com" ``` The name is the prefix only, as in the dashboard. `vercel dns list yourdomain.com` shows what is there. ## Check Ask Vercel's nameserver directly, before any cache: ```bash dig CNAME abc123._domainkey.yourdomain.com +short @ns1.vercel-dns.com ``` It should print the value from Charchy. The Domains page turns **Verified** once public resolvers see the records too. Charchy Send doesn't use your domain's SPF, so don't add one for it. If you already send mail from the domain, keep your one SPF record as it is: a name may have only one, and a second breaks SPF for every sender. --- # API keys and security > Test and live keys, full and sending-only permission, locking a key to a domain, keeping keys on the server — and what to do if one leaks. Source: https://charchy.krd/docs/api-keys Anyone holding a live key can send email as your domain and spend your balance. ## Kinds of key | | Test key | Live key | | ---------------- | --------------------------------------- | -------------------------- | | Starts with | `chy_test_` | `chy_live_` | | Sends real email | Never — simulated events, real webhooks | Yes | | `from` | Any domain | Your verified domains only | | Costs | Free, 1,000 recipients a day | Your plan and credits | | Use it in | Development, staging, CI | Production | Create keys under **API keys** in the dashboard. The full key is shown **once**; afterwards you see only its last four characters and when it was last used. Up to 20 active keys per workspace, live and test together; a revoked key frees its place. You accept the Charchy Send terms before your first live key. ## Permission * **Full** — send, read and list emails (`GET /v1/emails…`), reschedule and cancel them, check usage, upload images. * **Sending** — send, and check usage (`GET /v1/usage`, which holds no email data). Everything else answers `403 restricted_api_key`. A checkout service that sends receipts needs a sending key; only admin tools need a full one. ## Domain lock A live key can be **locked to one domain** (test keys can't). It then sends only from that domain; anything else answers `403 restricted_api_key`. If the domain is removed from the workspace, the key can't send at all — revoke it and make a new one. Use one locked key per product or brand, so a leak in one can't send as the others. ## Keep keys on the server * Read the key from an environment variable (e.g. `CHARCHY_SEND_KEY`) or your host's secret manager. * Never put a key in browser JavaScript, a mobile app, a public repository, a committed `.env` file, logs or error messages. * **The API sends no CORS headers**, on purpose: a request from browser code fails. Let your front end call your server. * Never prefix the variable with `NEXT_PUBLIC_` (Next.js) or `VITE_` (Vite) — those ship the value to every visitor. * One key per environment and per service, so you can revoke one without breaking the others. ## If a key leaks 1. **Revoke** the key under **API keys**. It stops working at once — the next request answers `401 invalid_api_key`. 2. **Create a new key** and put it in your server's environment. 3. Check **Emails** for anything you didn't send, and your balance. 4. If the key was in a Git repository, revoking is what matters: removing it from history doesn't un-leak it. A sudden jump in volume pauses sending automatically ([why](/docs/rate-limits#automatic-pauses)), which limits a leaked key — but revoke it as soon as you know. ## Webhook secrets Keep your webhook signing secret (`whsec_…`) in `CHARCHY_WEBHOOK_SECRET` on the server. If it leaks, **Rotate secret** in the dashboard; both secrets sign events for 24 hours while you deploy the new one ([Webhooks](/docs/webhooks#rotating-the-secret)). --- # Webhooks > Signed events to your server when an email is delivered, bounces or fails — the events, the payload, and how to verify the signature in Node, Laravel, Python and Go. Source: https://charchy.krd/docs/webhooks Webhooks tell your server what happened to each email. They follow the [Standard Webhooks](https://www.standardwebhooks.com) spec, so every major language has a library to verify them. ## Set up an endpoint In the dashboard, open **Webhooks**, add your endpoint's URL and pick the events. Put the **signing secret** (`whsec_…`) in your server's environment as `CHARCHY_WEBHOOK_SECRET`. * The URL must be `https://`, not a private network or `localhost`. We don't follow redirects. * Up to **5 endpoints** per workspace. * **Send test event** fires a sample of any event (marked `"test": true`) to that endpoint, whichever events it subscribes to, even while it is failing — not while it is disabled. * Emails sent with a [test key](/docs/test-mode), and mail to the magic addresses, fire real events too — the easiest end-to-end check. ## Events | Event | When | | ------------------------ | ----------------------------------------------------------------------------------------------------------------- | | `email.sent` | Our delivery infrastructure accepted the email. | | `email.delivered` | A recipient's mail server accepted it. | | `email.delivery_delayed` | A recipient's server is refusing for now; we keep trying. | | `email.bounced` | A recipient's server refused it. A permanent bounce suppresses the address. | | `email.complained` | A recipient marked it as spam. The address is suppressed. | | `email.failed` | It couldn't be sent, e.g. your domain stopped verifying. Refunded. | | `email.suppressed` | A recipient was skipped: it's on your suppression list. Not charged. | | `email.expired` | It couldn't leave before its `expires_at`, or waited 3 days past its due time while sending was paused. Refunded. | | `email.canceled` | You canceled it. Refunded. | | `domain.verified` | A sending domain is verified and ready to send from. | | `domain.failed` | A sending domain's verification failed, or a verified one lost its DKIM records. | | `account.paused` | Sending was paused for your workspace. | | `account.resumed` | Sending resumed. | | `balance.low` | 20% of your emails are left since your last top-up, and again when none are. | **One event per recipient.** `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained` and `email.suppressed` name their address in `data.recipient` — an email to three people sends one for each. `email.sent`, `email.failed`, `email.expired` and `email.canceled` come once per email. `scheduled`, `queued` and `unknown` send no event. Opens and clicks are not tracked: pixels and rewritten links hurt transactional mail. ## Payload Every event has the same envelope; `data` describes the email. ```json { "id": "evt_2b7k9x4m1q8w3n5p6r0s2t4v", "type": "email.delivered", "created_at": "2026-11-16T09:00:02.400Z", "data": { "email_id": "em_8f2k1x9q4w7m3n5p6r0s2t4v", "from": "Darin Game ", "to": ["customer@example.com"], "subject": "Your order #4821", "created_at": "2026-11-16T09:00:00.120Z", "tags": { "type": "order_confirmation" }, "test": false, "recipient": "customer@example.com" } } ``` * `id` equals the `webhook-id` header and stays the same on every retry. * `created_at` is when the event happened; `data.created_at` is when the email was accepted. * `data.test` is `true` when the email was sent with a test key (as on `GET /v1/emails/{id}`). The top-level `"test": true` marks a sample from **Send test event** instead. * Per-recipient events add `recipient`. * `email.bounced` adds `bounce`, `email.suppressed` adds `suppressed`, `email.failed` adds `failed` and `email.expired` adds `expired`, each saying why: ```json "bounce": { "type": "permanent", "sub_type": "no_email", "message": "The recipient's mail server refused the email: the address does not exist.", "diagnostic_code": "smtp; 550 5.1.1 user unknown" } ``` Full examples of every event: [Events reference](/docs/events). Payloads never carry the email's body; read more with [`GET /v1/emails/{id}`](/docs/send-email#read-an-email). A payload is at most 64 KB. ## Headers Every delivery is a `POST` with `content-type: application/json` and: | Header | Value | | ------------------- | ---------------------------------------------------------------- | | `webhook-id` | The event's id (`evt_…`). The same on every retry of that event. | | `webhook-timestamp` | When this attempt was signed, in Unix seconds. | | `webhook-signature` | `v1,` — one or more, separated by spaces. | | `user-agent` | `Charchy-Webhooks/1.0 (+https://charchy.krd/docs/webhooks)` | The signature is the HMAC-SHA256 of `..`, keyed with your secret (the base64 part after `whsec_`), encoded in base64. ## Verify every request Anyone can POST to your URL. Before you trust a request: 1. **Check the signature** against the **raw body** — the exact bytes received. Parsing and re-serialising the JSON changes the bytes, and the signature won't match. 2. **Reject timestamps more than 5 minutes old** (or ahead), so a captured request can't be replayed. 3. Compare in **constant time**. The Standard Webhooks libraries do all three. ### With a library ```ts // npm install @charchy/send — Next.js Route Handler: app/api/webhooks/charchy/route.ts import { verifyWebhook, WebhookVerificationError } from "@charchy/send" export async function POST(request: Request) { try { // The raw body; the secret defaults to CHARCHY_WEBHOOK_SECRET. const event = await verifyWebhook({ payload: await request.text(), headers: request.headers }) await enqueueCharchyEvent(event) // typed, camelCased; switch (event.type) narrows event.data return new Response(null, { status: 204 }) } catch (error) { if (error instanceof WebhookVerificationError) return new Response("Invalid signature", { status: 400 }) throw error } } ``` ```ts // npm install standardwebhooks import { Webhook } from "standardwebhooks" const webhook = new Webhook(process.env.CHARCHY_WEBHOOK_SECRET!) // Next.js Route Handler: app/api/webhooks/charchy/route.ts export async function POST(request: Request) { const body = await request.text() // the raw body let event: { id: string; type: string; data: Record } try { event = webhook.verify(body, Object.fromEntries(request.headers)) as typeof event } catch { return new Response("Invalid signature", { status: 400 }) } await enqueueCharchyEvent(event) // your queue; do the work later return new Response(null, { status: 204 }) } ``` ```php preventRequestForgery(except: ['webhooks/charchy']); // (Laravel 11 and 12: validateCsrfTokens(except: [...])) namespace App\Http\Controllers; use App\Jobs\HandleCharchyEvent; use Illuminate\Http\Request; use Illuminate\Http\Response; use StandardWebhooks\Exception\WebhookVerificationException; use StandardWebhooks\Webhook; class CharchyWebhookController { public function __invoke(Request $request): Response { // The whole "whsec_…" secret; the library drops the prefix itself. $webhook = new Webhook(config('services.charchy_send.webhook_secret')); try { $event = $webhook->verify($request->getContent(), [ // the raw body 'webhook-id' => $request->header('webhook-id'), 'webhook-timestamp' => $request->header('webhook-timestamp'), 'webhook-signature' => $request->header('webhook-signature'), ]); } catch (WebhookVerificationException) { return response('Invalid signature', 400); } HandleCharchyEvent::dispatch($event); // your queued job; do the work later return response()->noContent(); } } ``` ```python # pip install standardwebhooks import os from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from standardwebhooks.webhooks import Webhook webhook = Webhook(os.environ["CHARCHY_WEBHOOK_SECRET"]) @csrf_exempt @require_POST def charchy_webhook(request): try: event = webhook.verify(request.body, dict(request.headers)) # raw body except Exception: return HttpResponse("Invalid signature", status=400) enqueue_charchy_event(event) # your queue; do the work later return HttpResponse(status=204) ``` ```go // go get github.com/standard-webhooks/standard-webhooks/libraries/go import ( "io" "net/http" "os" standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go" ) func charchyWebhook(w http.ResponseWriter, r *http.Request) { webhook, err := standardwebhooks.NewWebhook(os.Getenv("CHARCHY_WEBHOOK_SECRET")) if err != nil { http.Error(w, "bad secret", http.StatusInternalServerError) return } body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // the raw body if err != nil || webhook.Verify(body, r.Header) != nil { http.Error(w, "invalid signature", http.StatusBadRequest) return } enqueueCharchyEvent(body) // your queue; do the work later w.WriteHeader(http.StatusNoContent) } ``` ### With plain HMAC ```ts import { createHmac, timingSafeEqual } from "node:crypto" export function verifyCharchyWebhook(rawBody: string, headers: Headers, secret: string) { const id = headers.get("webhook-id") const timestamp = headers.get("webhook-timestamp") const signatures = headers.get("webhook-signature") if (!id || !timestamp || !signatures) throw new Error("Missing webhook headers") const age = Math.abs(Date.now() / 1000 - Number(timestamp)) if (!(age <= 5 * 60)) throw new Error("Timestamp too old") const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64") const expected = createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest() const valid = signatures.split(" ").some((entry) => { const [version, signature] = entry.split(",") if (version !== "v1" || !signature) return false const received = Buffer.from(signature, "base64") return received.length === expected.length && timingSafeEqual(received, expected) }) if (!valid) throw new Error("Invalid signature") return JSON.parse(rawBody) } ``` ```php middleware(VerifyCharchyWebhook::class) namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\Response; class VerifyCharchyWebhook { public function handle(Request $request, Closure $next): Response { $id = (string) $request->header('webhook-id'); $timestamp = (string) $request->header('webhook-timestamp'); $signatures = (string) $request->header('webhook-signature'); abort_unless(ctype_digit($timestamp) && abs(time() - (int) $timestamp) <= 300, 400, 'Stale timestamp'); $key = base64_decode(Str::after(config('services.charchy_send.webhook_secret'), 'whsec_')); $expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$request->getContent()}", $key, true)); foreach (explode(' ', $signatures) as $entry) { [$version, $signature] = array_pad(explode(',', $entry, 2), 2, ''); if ($version === 'v1' && hash_equals($expected, $signature)) { return $next($request); } } abort(400, 'Invalid signature'); } } ``` ```python import base64 import hashlib import hmac import json import time def verify_charchy_webhook(raw_body: bytes, headers, secret: str) -> dict: msg_id = headers["webhook-id"] timestamp = headers["webhook-timestamp"] signatures = headers["webhook-signature"] if abs(time.time() - int(timestamp)) > 5 * 60: raise ValueError("Timestamp too old") key = base64.b64decode(secret.removeprefix("whsec_")) signed = f"{msg_id}.{timestamp}.".encode() + raw_body expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode() for entry in signatures.split(" "): version, _, signature = entry.partition(",") if version == "v1" and hmac.compare_digest(signature, expected): return json.loads(raw_body) raise ValueError("Invalid signature") ``` ```go import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "errors" "net/http" "strconv" "strings" "time" ) func verifyCharchyWebhook(rawBody []byte, header http.Header, secret string) error { id := header.Get("webhook-id") timestamp := header.Get("webhook-timestamp") signatures := header.Get("webhook-signature") seconds, err := strconv.ParseInt(timestamp, 10, 64) if err != nil { return errors.New("bad timestamp") } if age := time.Since(time.Unix(seconds, 0)); age > 5*time.Minute || age < -5*time.Minute { return errors.New("timestamp too old") } key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_")) if err != nil { return errors.New("bad secret") } mac := hmac.New(sha256.New, key) mac.Write([]byte(id + "." + timestamp + ".")) mac.Write(rawBody) expected := mac.Sum(nil) for _, entry := range strings.Split(signatures, " ") { version, signature, ok := strings.Cut(entry, ",") if !ok || version != "v1" { continue } received, err := base64.StdEncoding.DecodeString(signature) if err == nil && hmac.Equal(received, expected) { return nil } } return errors.New("invalid signature") } ``` In **Express**, use `express.raw({ type: "application/json" })` on the webhook route — `express.json()` hands you parsed JSON — and pass `req.body` and `req.headers` to `verifyWebhook` ([SDK](/docs/sdks/node#verify-webhooks)). ## Answer fast, work later * Answer **2xx within 5 seconds**. Slower is a failure and is retried. * Do the real work **after** answering, from a queue or background job. * Any `2xx` means "received". `410 Gone` disables the endpoint. Anything else is retried. ## Duplicates and order * **Expect duplicates.** A retry after a timeout can redeliver an event you handled. Store each processed `webhook-id` and skip repeats. * **Order is not guaranteed.** `email.delivered` can arrive before `email.sent`. Order by `created_at`, and never move an email's status backwards in your database. ## Retries A failed delivery is retried immediately, then after 5 seconds, 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours and 10 hours — about 28 hours in all. * After **5 failures in a row**, the endpoint is **failing**: new events wait in a queue. The oldest waiting event is retried on the schedule above as a probe; if it runs out of attempts it is marked failed, and the next waiting event becomes the probe 10 hours later. The first success (the probe's, or a **Send test event**) marks the endpoint healthy and sends the waiting events, at most 3 at a time. * After **3 days** of failing — or at once on `410 Gone` — the endpoint is **disabled** and your workspace's owners and admins get an email. Waiting events are kept: **Enable** the endpoint within 3 days and they are sent. After that they are marked failed — still in the log, and **Replay all failed since…** sends them. The delivery log keeps every attempt for **30 days** — request, response code, the start of your reply, and how long it took — with **Replay** for one event or **Replay all failed since…**. Down for longer? `GET /v1/emails/{id}` always has the current status. ## Rotating the secret **Rotate secret** starts a new secret. For the next 24 hours every event is signed with both the old and the new one (two `v1,…` entries in `webhook-signature`), so you can deploy the new secret without losing an event. The libraries and the code above accept any matching signature. Rotating again within those 24 hours drops the oldest secret: only the two newest sign. --- # Events reference > One full payload example for every webhook event — email, domain and account events. Source: https://charchy.krd/docs/events Every event has this envelope. `id` is also the `webhook-id` header; `created_at` is when the event happened. Receiving and verifying: [Webhooks](/docs/webhooks). ```json { "id": "evt_…", "type": "email.delivered", "created_at": "2026-11-16T09:00:02.400Z", "data": { } } ``` ## Email events Every email event's `data` has `email_id`, `from`, `to`, `subject`, `created_at` (when the email was accepted) and `tags`. **One event per recipient.** `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained` and `email.suppressed` are about one address, named in `recipient` (possibly a `cc` or `bcc` address). An email to three people sends three `email.delivered` — or two, and one `email.bounced`. `email.sent`, `email.failed`, `email.expired` and `email.canceled` come once per email, with no `recipient`. The email's own status, as [`GET /v1/emails/{id}`](/docs/send-email#read-an-email) returns it, sums up its recipients: `complained` if any complained, else `bounced` if any bounced, else `delivered` once every one was delivered, else `delivery_delayed` if any is delayed, else `sent`. [Test-key](/docs/test-mode) emails and mail to the magic addresses send these events too — simulated, same shape; a test key's carry `"test": true` in `data`. `scheduled`, `queued` and `unknown` have no event: the API's answer already told you the first two, and `unknown` is not an ending (see [`unknown`](/docs/send-email#unknown)). ### `email.sent` Our delivery infrastructure accepted the email and is handing it to the recipient's mail server. ```json { "id": "evt_1a7k2m9x4q8w3n5p6r0s2t4v", "type": "email.sent", "created_at": "2026-11-16T09:00:00.910Z", "data": { "email_id": "em_8f2k1x9q4w7m3n5p6r0s2t4v", "from": "Darin Game ", "to": ["customer@example.com"], "subject": "Your order #4821", "created_at": "2026-11-16T09:00:00.120Z", "tags": { "type": "order_confirmation" }, "test": false } } ``` ### `email.delivered` The recipient's mail server accepted the email. Inbox or spam is the receiving provider's decision. ```json { "id": "evt_2b7k9x4m1q8w3n5p6r0s2t4v", "type": "email.delivered", "created_at": "2026-11-16T09:00:02.400Z", "data": { "email_id": "em_8f2k1x9q4w7m3n5p6r0s2t4v", "from": "Darin Game ", "to": ["customer@example.com"], "subject": "Your order #4821", "created_at": "2026-11-16T09:00:00.120Z", "tags": { "type": "order_confirmation" }, "test": false, "recipient": "customer@example.com" } } ``` ### `email.delivery_delayed` The receiving server is refusing for now (a full mailbox, a busy server). We keep trying; `email.delivered` or `email.bounced` follows. ```json { "id": "evt_3c8m1q4w7k2x3n5p6r0s2t4v", "type": "email.delivery_delayed", "created_at": "2026-11-16T09:05:00.000Z", "data": { "email_id": "em_8f2k1x9q4w7m3n5p6r0s2t4v", "from": "Darin Game ", "to": ["customer@example.com"], "subject": "Your order #4821", "created_at": "2026-11-16T09:00:00.120Z", "tags": { "type": "order_confirmation" }, "test": false, "recipient": "customer@example.com" } } ``` ### `email.bounced` The receiving server refused the email for this recipient. A `permanent` bounce means the address doesn't exist: it is suppressed, and later emails skip it. A `transient` one (a full mailbox, a message too large) is not suppressed — the server kept refusing until we stopped retrying. `sub_type` is one of `general`, `no_email`, `suppressed`, `on_account_suppression_list`, `mailbox_full`, `message_too_large`, `content_rejected`, `attachment_rejected`; `message` says it in words, and `diagnostic_code` is the receiving server's own answer when it gave one. ```json { "id": "evt_6m1q8w2b7k9x3n5p6r0s2t4v", "type": "email.bounced", "created_at": "2026-11-16T09:00:03.100Z", "data": { "email_id": "em_3n8v2c7x1k5d3n5p6r0s2t4v", "from": "Darin Game ", "to": ["old-address@example.com"], "subject": "Your November invoice", "created_at": "2026-11-16T09:00:00.500Z", "tags": { "type": "invoice" }, "test": false, "recipient": "old-address@example.com", "bounce": { "type": "permanent", "sub_type": "no_email", "message": "The recipient's mail server refused the email: the address does not exist.", "diagnostic_code": "smtp; 550 5.1.1 user unknown" } } } ``` ### `email.complained` The recipient marked the email as spam. The address is suppressed for the API and for your Campaigns. It usually follows an `email.delivered` for the same recipient, sometimes days later. ```json { "id": "evt_4d9n2r5t8w1y3n5p6r0s2t4v", "type": "email.complained", "created_at": "2026-11-16T11:42:10.000Z", "data": { "email_id": "em_8f2k1x9q4w7m3n5p6r0s2t4v", "from": "Darin Game ", "to": ["customer@example.com"], "subject": "Your order #4821", "created_at": "2026-11-16T09:00:00.120Z", "tags": { "type": "order_confirmation" }, "test": false, "recipient": "customer@example.com" } } ``` ### `email.failed` The email couldn't be sent and won't be retried — for example, its domain stopped verifying before a scheduled email's time came, or our delivery infrastructure refused it (a virus in an attachment). `failed.reason` says why in words. Refunded. ```json { "id": "evt_5e1p3s6v9x2z3n5p6r0s2t4v", "type": "email.failed", "created_at": "2026-11-20T06:00:00.300Z", "data": { "email_id": "em_5k2m8x1q9w3r3n5p6r0s2t4v", "from": "Clinic ", "to": ["patient@example.com"], "subject": "Reminder: your appointment tomorrow at 10:00", "created_at": "2026-11-16T14:00:00.000Z", "tags": { "type": "booking_reminder" }, "test": false, "failed": { "reason": "clinic.example is no longer verified." } } } ``` ### `email.suppressed` This recipient is on your suppression list (an earlier hard bounce or spam complaint), so it was skipped and not charged — one event per skipped recipient. When every recipient was skipped, nothing is sent and the email's status is `suppressed`. ```json { "id": "evt_7g2r4v7y1b3d3n5p6r0s2t4v", "type": "email.suppressed", "created_at": "2026-11-16T09:10:00.050Z", "data": { "email_id": "em_9t3y6v1j407p3n5p6r0s2t4v", "from": "Darin Game ", "to": ["old-address@example.com"], "subject": "Your order #4830", "created_at": "2026-11-16T09:10:00.040Z", "tags": { "type": "order_confirmation" }, "test": false, "recipient": "old-address@example.com", "suppressed": { "reason": "previous_bounce" } } } ``` `reason` is `previous_bounce` or `previous_complaint`. Mail to `suppressed@sim.charchy.krd` reads `previous_bounce`. ### `email.expired` Dropped because it couldn't leave in time: its `expires_at` passed, or it waited 3 days past its due time while sending was paused. `expired.reason` says which. Refunded. ```json { "id": "evt_8h3s5v8z2c4f3n5p6r0s2t4v", "type": "email.expired", "created_at": "2026-11-16T12:10:00.000Z", "data": { "email_id": "em_2w5e8r1t4y7v3n5p6r0s2t4v", "from": "My App ", "to": ["user@example.com"], "subject": "Your sign-in code: 482910", "created_at": "2026-11-16T12:00:00.000Z", "tags": { "type": "signin_code" }, "test": false, "expired": { "reason": "It could not leave before its expires_at, so it was dropped." } } } ``` ### `email.canceled` You canceled the email before it left. Refunded. ```json { "id": "evt_9j4t6w9a3d5g3n5p6r0s2t4v", "type": "email.canceled", "created_at": "2026-11-17T08:30:00.000Z", "data": { "email_id": "em_5k2m8x1q9w3r3n5p6r0s2t4v", "from": "Clinic ", "to": ["patient@example.com"], "subject": "Reminder: your appointment tomorrow at 10:00", "created_at": "2026-11-16T14:00:00.000Z", "tags": { "type": "booking_reminder" }, "test": false } } ``` ## Domain events ### `domain.verified` The domain's DNS records checked out: you can send from any address on it now. ```json { "id": "evt_0k5v7x1b4e6h3n5p6r0s2t4v", "type": "domain.verified", "created_at": "2026-11-16T08:12:00.000Z", "data": { "domain": "daringaming.com" } } ``` ### `domain.failed` Verification failed: the DKIM records weren't found within 72 hours, setup failed, or a verified domain's records went missing at two daily re-checks a few hours apart. Emails from it answer `domain_not_verified`. Check the records on the Domains page; a domain whose records are put back sends `domain.verified` again by itself ([if a domain stops verifying](/docs/domains#if-a-domain-stops-verifying)). ```json { "id": "evt_116v8y2c5f7j3n5p6r0s2t4v", "type": "domain.failed", "created_at": "2026-11-19T03:00:00.000Z", "data": { "domain": "daringaming.com" } } ``` ## Account events ### `account.paused` Sending is paused for your workspace — by our safety checks or our team. New live requests answer `sending_paused`; accepted emails are held and go out when sending resumes (unless their `expires_at` passes, or they wait 3 days — then they expire and are refunded). Test keys keep working. Your owners and admins also get an email. `code` is `bounce_rate`, `complaint_rate`, `not_transactional`, `provider_paused`, `reputation_finding` or `manual`; `reason` says it in words, with our numbers when we have them. `volume_spike` no longer pauses sending (only events from before 2026-11-17 carry it). ```json { "id": "evt_2m7w9z3d6g8k3n5p6r0s2t4v", "type": "account.paused", "created_at": "2026-11-18T15:00:00.000Z", "data": { "code": "bounce_rate", "reason": "Too many of your recent emails bounced (hard bounces — addresses that do not exist). Sending to lists of addresses nobody gave you is the usual cause. Details: 4.20% hard bounces over the last 500 recipients" } } ``` ### `account.resumed` ```json { "id": "evt_3n8x1a4e7h913n5p6r0s2t4v", "type": "account.resumed", "created_at": "2026-11-19T10:00:00.000Z", "data": {} } ``` ### `balance.low` Your emails — this term's plan emails plus usable credits, as in the `x-charchy-emails-remaining` header — are running out. * `used_percent: 80` — what is left fell to 20% of what you had after your last top-up. * `used_percent: 100` — nothing is left. Live sends answer `402 insufficient_balance` until you top up. A top-up is a plan term starting (bought, renewed, or a paid-ahead term taking over) or credits added. Each threshold fires once per top-up, from a send; an ended term or expired credits don't fire it (you get emails about those). `emails_left` is what's left now. ```json { "id": "evt_4p9y2b5f8j1m3n5p6r0s2t4v", "type": "balance.low", "created_at": "2026-11-25T17:20:00.000Z", "data": { "used_percent": 80, "emails_left": 2000 } } ``` ## Test events **Send test event** in the dashboard sends any of these with `"test": true` at the top level, next to `id` — to that endpoint only, whichever events it subscribes to, even while it is failing. `data.test` is different: on every `email.*` event, `true` when the email was sent with a [test key](/docs/test-mode) — the same as `test` on [`GET /v1/emails/{id}`](/docs/send-email#read-an-email). A sample from **Send test event** has `"test": true` at the top and `"test": false` in `data`. --- # Next.js > Send email from a Next.js App Router app — a Server Action, a Route Handler, React Email, a one-line webhook endpoint, and an end-to-end check with the magic addresses. Source: https://charchy.krd/docs/guides/nextjs ## 1. Install and set the key ```bash npm install @charchy/send ``` ```bash pnpm add @charchy/send ``` ```bash yarn add @charchy/send ``` ```bash bun add @charchy/send ``` ```ini title=".env.local" CHARCHY_SEND_KEY=chy_test_… CHARCHY_SEND_FROM="My App " CHARCHY_WEBHOOK_SECRET=whsec_… ``` Never a `NEXT_PUBLIC_` variable: those are bundled into the browser. On Vercel, add the same three under **Settings → Environment Variables**. ## 2. The client ```ts title="lib/charchy-send.ts" import "server-only" import { CharchySend } from "@charchy/send" /** Reads CHARCHY_SEND_KEY when an email is sent, not now: `next build` never needs the key. */ export const send = new CharchySend() export const FROM = process.env.CHARCHY_SEND_FROM! // "My App " ``` Creating the client reads no key — the key is read when an email is sent — so `next build`, which imports every route module, runs fine without it. With no key at run time, a send returns `missing_api_key` and nothing goes out. `server-only` turns an import from a Client Component into a build error. ## 3. From a Server Action ```ts title="app/invite/actions.ts" "use server" import { FROM, send } from "@/lib/charchy-send" export type InviteState = { sent: boolean; error?: string } export async function sendInvite(_previous: InviteState, formData: FormData): Promise { // A Server Action is a public POST endpoint: check the session and permission here. const email = String(formData.get("email")) const inviteId = crypto.randomUUID() // in your app: the id of the invitation you just saved const { error } = await send.emails.send( { from: FROM, to: email, subject: "You're invited to My App", html: `

Accept the invitation

`, tags: { type: "invite" }, }, { idempotencyKey: `invite/${inviteId}` } ) if (error) { console.error(error.code, error.requestId) return { sent: false, error: error.code === "validation_error" ? "Check the address." : "Couldn't send. Try again." } } return { sent: true } } ``` ```tsx title="app/invite/invite-form.tsx" "use client" import { useActionState } from "react" import { sendInvite } from "./actions" export function InviteForm() { const [state, action, pending] = useActionState(sendInvite, { sent: false }) return (
{state.error &&

{state.error}

} {state.sent &&

Invitation sent.

}
) } ``` The SDK never throws: every call resolves to `{ data, error }`. It retries network errors, `5xx` and `429` itself, with the same idempotency key — no retry loop of your own. ## 4. From a Route Handler, with React Email ```bash npm install @react-email/render @react-email/components ``` ```tsx title="emails/welcome.tsx" import { Body, Button, Html, Preview, Text } from "@react-email/components" export function WelcomeEmail({ name }: { name: string }) { return ( Welcome to My App Welcome, {name}. ) } ``` ```ts title="app/api/send/route.ts" import { FROM, send } from "@/lib/charchy-send" import { WelcomeEmail } from "@/emails/welcome" export async function POST(request: Request) { // Your auth check here, then read what you need from the request. const { userId, email, name } = (await request.json()) as { userId: string; email: string; name: string } const { data, error } = await send.emails.send( { from: FROM, to: email, subject: "Welcome to My App", react: WelcomeEmail({ name }), // rendered to html with @react-email/render tags: { type: "welcome" }, }, { idempotencyKey: `welcome/${userId}` } ) if (error) return Response.json({ error: error.code }, { status: error.statusCode ?? 502 }) return Response.json({ id: data.id }) } ``` `react` needs `@react-email/render` (Node 20+); without it the call returns `react_render_error`. Route Handlers run on Node.js by default — leave out a `runtime` export; the Edge runtime is deprecated. ### Don't make the person wait When the email isn't the answer to the request, send it after the response with `after()` (on Vercel it runs inside `waitUntil`): ```ts title="app/api/signup/route.ts" import { after } from "next/server" import { FROM, send } from "@/lib/charchy-send" export async function POST(request: Request) { const { email } = (await request.json()) as { email: string } const user = await createUser(email) // Answer now; send once the response is out. after(async () => { const { error } = await send.emails.send( { from: FROM, to: user.email, subject: "Welcome", text: "Glad you're here." }, { idempotencyKey: `welcome/${user.id}` } ) if (error) console.error("welcome email", error.code, error.requestId) }) return Response.json({ id: user.id }, { status: 201 }) } ``` Sign-in codes from [Better Auth](/docs/guides/better-auth) go the same way, through its `advanced.backgroundTasks` option. ## 5. Webhooks in one line ```ts title="app/api/webhooks/charchy/route.ts" import { webhookHandler } from "@charchy/send" export const POST = webhookHandler({ "email.bounced": (event) => markUndeliverable(event.data.recipient, `bounced: ${event.data.bounce.type}`), "email.complained": (event) => markUndeliverable(event.data.recipient, "complained"), }) ``` It verifies the signature on the raw body with `CHARCHY_WEBHOOK_SECRET`, runs the handler for that event type, and answers `204` — `400` to a bad signature, `500` when a handler throws, so the event is sent again. Handlers run before the answer, which must come within 5 seconds: hand slow work to `after()` or a queue. In the dashboard, under **Webhooks**, add `https://myapp.com/api/webhooks/charchy`. More: [Webhooks](/docs/webhooks), [`verifyWebhook`](/docs/sdks/node#verify-webhooks) to do it yourself. ## 6. Check it end to end With a test key, the [magic addresses](/docs/test-mode#magic-addresses) play out a known outcome, free: ```ts title="scripts/email-check.ts" // npx tsx --env-file=.env.local scripts/email-check.ts import { CharchySend, unwrap } from "@charchy/send" const send = new CharchySend() for (const outcome of ["delivered", "bounced"] as const) { const sent = await send.emails .send( { from: "My App ", to: send.test.address(outcome, "nextjs"), subject: "Check", text: "ok" }, { idempotencyKey: `email-check/${outcome}/${Date.now()}` } ) .then(unwrap) const email = await send.emails.waitFor(sent.id, { until: [outcome], timeoutMs: 30_000 }).then(unwrap) console.log(outcome, email.id, email.status) } ``` The bounce also reaches your webhook endpoint as `email.bounced` (deployed, or through a tunnel to `localhost`). For CI, see [Testing in CI](/docs/guides/testing-in-ci). ## Pages Router The same client works in `pages/api`. For webhooks, turn off the body parser so the signature can be checked against the exact bytes: ```ts title="pages/api/webhooks/charchy.ts" import type { NextApiRequest, NextApiResponse } from "next" import { verifyWebhook, type WebhookEvent } from "@charchy/send" export const config = { api: { bodyParser: false } } export default async function handler(req: NextApiRequest, res: NextApiResponse) { const chunks: Buffer[] = [] for await (const chunk of req) chunks.push(chunk as Buffer) let event: WebhookEvent try { event = await verifyWebhook({ payload: Buffer.concat(chunks), headers: req.headers }) } catch { return res.status(400).send("Invalid signature") } await handleCharchyEvent(event) res.status(204).end() } ``` --- # Convex > Send email from Convex — scheduled from the mutation that writes the record, so it goes only if the write commits; an action with an idempotency key and retries; webhooks into an HTTP action; and sign-in codes with Better Auth on Convex. Source: https://charchy.krd/docs/guides/convex `@charchy/send` runs in Convex's default runtime: it needs only `fetch` and Web Crypto. No `"use node"`. ## 1. Install and set the key ```bash npm install @charchy/send ``` ```bash pnpm add @charchy/send ``` ```bash yarn add @charchy/send ``` ```bash bun add @charchy/send ``` ```bash npx convex env set CHARCHY_SEND_KEY chy_test_… npx convex env set CHARCHY_SEND_FROM "My App " npx convex env set CHARCHY_WEBHOOK_SECRET whsec_… ``` Each deployment has its own variables: set a live key (`chy_live_…`) on production with `--prod`, or in the dashboard under **Settings → Environment Variables**. ## 2. Send only if the write commits Mutations can't call `fetch`, and they are transactional. So the mutation that saves the record **schedules** the send: `runAfter` from a mutation is part of the transaction — if the mutation fails, nothing is scheduled. ```ts title="convex/schema.ts" import { defineSchema, defineTable } from "convex/server" import { v } from "convex/values" export default defineSchema({ orders: defineTable({ email: v.string(), total: v.number(), receiptEmailId: v.optional(v.string()), // "em_…", once Charchy Send accepted it receiptStatus: v.optional(v.string()), // "delivered", "bounced", … from webhooks receiptStatusAt: v.optional(v.number()), }), }) ``` ```ts title="convex/orders.ts" import { v } from "convex/values" import { internal } from "./_generated/api" import { internalMutation, internalQuery, mutation } from "./_generated/server" export const place = mutation({ args: { email: v.string(), total: v.number() }, handler: async (ctx, args) => { const orderId = await ctx.db.insert("orders", args) // Scheduled only if this mutation commits: no receipt for an order that was never saved. await ctx.scheduler.runAfter(0, internal.emails.sendReceipt, { orderId }) return orderId }, }) export const get = internalQuery({ args: { orderId: v.id("orders") }, handler: (ctx, { orderId }) => ctx.db.get(orderId), }) export const saveReceiptEmailId = internalMutation({ args: { orderId: v.id("orders"), emailId: v.string() }, handler: (ctx, { orderId, emailId }) => ctx.db.patch(orderId, { receiptEmailId: emailId }), }) ``` ## 3. The action that sends ```ts title="convex/emails.ts" import { CharchySend, type CharchySendError } from "@charchy/send" import { v } from "convex/values" import { internal } from "./_generated/api" import { internalAction } from "./_generated/server" /** Reads CHARCHY_SEND_KEY when an email is sent, so pushing never needs the key. */ const send = new CharchySend() const MAX_ATTEMPTS = 5 export const sendReceipt = internalAction({ args: { orderId: v.id("orders"), attempt: v.optional(v.number()) }, handler: async (ctx, { orderId, attempt = 1 }) => { const order = await ctx.runQuery(internal.orders.get, { orderId }) if (!order || order.receiptEmailId) return // gone, or already sent const { data, error } = await send.emails.send( { from: process.env.CHARCHY_SEND_FROM!, to: order.email, subject: "Your receipt", html: `

Thanks! You paid ${order.total.toFixed(2)} USD.

`, tags: { type: "receipt", order_id: orderId }, }, // From the document: every retry, the SDK's or ours, is the same email. { idempotencyKey: `receipt/${orderId}` } ) if (error) { if (isWorthRetrying(error) && attempt < MAX_ATTEMPTS) { const delayMs = (error.retryAfterSeconds ?? 60 * 2 ** attempt) * 1000 await ctx.scheduler.runAfter(delayMs, internal.emails.sendReceipt, { orderId, attempt: attempt + 1 }) return } throw error // in the Convex logs, with error.code, error.docs and error.requestId } await ctx.runMutation(internal.orders.saveReceiptEmailId, { orderId, emailId: data.id }) }, }) /** An outage or a busy moment. A refusal (402, 403, 422…) won't change on a retry. */ function isWorthRetrying(error: CharchySendError): boolean { return ( error.code === "network_error" || error.code === "rate_limit_exceeded" || error.code === "daily_limit_reached" || error.code === "idempotency_in_flight" || (error.statusCode !== null && error.statusCode >= 500) ) } ``` * **One client at the top of the file.** Creating it reads no key — the key is read when an email is sent — so pushing works on a deployment without `CHARCHY_SEND_KEY`; a send there returns `missing_api_key` and nothing goes out. * **Retries.** Convex runs a scheduled action at most once and never retries it. The SDK already retries quick failures (2 more tries within the call); for a longer outage the action schedules itself again — 2, 4, 8, 16 minutes, or the API's `Retry-After`. The idempotency key comes from the order id, so a retry can never send a second receipt: within 24 hours the API answers it with the first email's id. For many emails, the [Workpool](https://www.convex.dev/components/workpool) or [Action Retrier](https://www.convex.dev/components/retrier) components do the same with backoff and limits. * **The `em_…` id** goes back on the document through an internal mutation; `order.receiptEmailId` also stops a second run before it calls the API. * **The `order_id` tag** comes back on every webhook event for this email. ## 4. Webhooks into an HTTP action ```ts title="convex/http.ts" import { verifyWebhook, WebhookVerificationError } from "@charchy/send" import { httpRouter } from "convex/server" import { internal } from "./_generated/api" import { httpAction } from "./_generated/server" const http = httpRouter() const RECEIPT_STATUSES = { "email.delivered": "delivered", "email.bounced": "bounced", "email.complained": "complained", } as const http.route({ path: "/webhooks/charchy", method: "POST", handler: httpAction(async (ctx, request) => { let event try { // The raw body; the secret defaults to CHARCHY_WEBHOOK_SECRET. event = await verifyWebhook({ payload: await request.text(), headers: request.headers }) } catch (error) { if (error instanceof WebhookVerificationError) return new Response("Invalid signature", { status: 400 }) throw error } if (event.type === "email.delivered" || event.type === "email.bounced" || event.type === "email.complained") { const orderId = event.data.tags.order_id // the tag sendReceipt set if (orderId) { await ctx.runMutation(internal.orders.recordReceiptStatus, { orderId, status: RECEIPT_STATUSES[event.type], at: Date.parse(event.createdAt), }) } } return new Response(null, { status: 204 }) }), }) export default http ``` The mutation it calls, next to the others in `convex/orders.ts`: ```ts title="convex/orders.ts" export const recordReceiptStatus = internalMutation({ args: { orderId: v.string(), status: v.string(), at: v.number() }, handler: async (ctx, { orderId, status, at }) => { const id = ctx.db.normalizeId("orders", orderId) const order = id && (await ctx.db.get(id)) // Events can arrive twice and out of order: never let an older one win. if (!order || (order.receiptStatusAt ?? 0) > at) return await ctx.db.patch(order._id, { receiptStatus: status, receiptStatusAt: at }) }, }) ``` In the Charchy dashboard, under **Webhooks**, add your deployment's HTTP actions URL — it ends in `.convex.site`, not `.convex.cloud` — plus the path: `https://.convex.site/webhooks/charchy`. A thrown error answers `500`, and the event is sent again; the mutation ignores a repeat. Shorter, when every handler is quick: ```ts import { webhookHandler } from "@charchy/send" http.route({ path: "/webhooks/charchy", method: "POST", handler: httpAction((ctx, request) => webhookHandler({ "email.bounced": (event) => ctx.runMutation(internal.orders.recordReceiptStatus, { orderId: event.data.tags.order_id ?? "", status: "bounced", at: Date.parse(event.createdAt), }), })(request) ), }) ``` ## 5. Sign-in codes with Better Auth on Convex With [`@convex-dev/better-auth`](https://labs.convex.dev/better-auth) (set up as in its guide for your framework), the `emailOTP` callback schedules the send instead of waiting for it: ```ts title="convex/auth.ts" import { createClient, type GenericCtx } from "@convex-dev/better-auth" import { convex } from "@convex-dev/better-auth/plugins" import { requireRunMutationCtx } from "@convex-dev/better-auth/utils" import { betterAuth } from "better-auth/minimal" import { emailOTP } from "better-auth/plugins" import { components, internal } from "./_generated/api" import type { DataModel } from "./_generated/dataModel" import authConfig from "./auth.config" const CODE_LIFETIME_SECONDS = 5 * 60 export const authComponent = createClient(components.betterAuth) export const createAuth = (ctx: GenericCtx) => betterAuth({ baseURL: process.env.SITE_URL, database: authComponent.adapter(ctx), plugins: [ emailOTP({ expiresIn: CODE_LIFETIME_SECONDS, async sendVerificationOTP({ email, otp, type }) { // Scheduled, not awaited: the request doesn't wait on the email // (Better Auth's advice against timing attacks), and the send runs // in an action of its own. await requireRunMutationCtx(ctx).scheduler.runAfter(0, internal.emails.sendSignInCode, { email, otp, type, expiresAt: Date.now() + CODE_LIFETIME_SECONDS * 1000, }) }, }), convex({ authConfig }), ], }) ``` The action, next to `sendReceipt`: ```ts title="convex/emails.ts" export const sendSignInCode = internalAction({ args: { email: v.string(), otp: v.string(), type: v.string(), expiresAt: v.number() }, handler: async (ctx, { email, otp, type, expiresAt }) => { const { error } = await send.emails.send( { from: process.env.CHARCHY_SEND_FROM!, to: email, subject: `Your code: ${otp}`, text: `Your code is ${otp}. It expires in 5 minutes.`, expiresAt: new Date(expiresAt), // dropped and refunded if it can't leave in time tags: { type: type.replaceAll("-", "_") }, }, { idempotencyKey: `otp/${type}/${email}/${otp}` } ) if (error) throw error }, }) ``` The auth routes run as HTTP actions, and server-side `auth.api` calls from a mutation carry a scheduler too; `requireRunMutationCtx` throws if a query ever reaches the callback. The same pattern fits `sendResetPassword`, `sendVerificationEmail` and `magicLink`'s `sendMagicLink` — see [Better Auth](/docs/guides/better-auth) for their options. ## 6. Try it ```bash npx convex run orders:place '{"email": "delivered@sim.charchy.krd", "total": 12.5}' ``` The receipt shows on the Charchy dashboard's **Emails** page; a moment later the `email.delivered` webhook sets `receiptStatus` on the order. Use `bounced@sim.charchy.krd` for the bounce path — [magic addresses](/docs/test-mode#magic-addresses). --- # Sign-in codes with Better Auth > Send Better Auth's one-time codes, magic links, verification emails and password resets through Charchy Send, with expiring codes, idempotency keys and sending after the response. Source: https://charchy.krd/docs/guides/better-auth [Better Auth](https://www.better-auth.com) calls a function you give it with the code or link. Make that function call Charchy Send. Written for Better Auth 1.7 with Next.js; on [Convex](/docs/guides/convex#5-sign-in-codes-with-better-auth-on-convex), schedule the send instead. ```bash npm install @charchy/send ``` ```bash pnpm add @charchy/send ``` ```bash yarn add @charchy/send ``` ```bash bun add @charchy/send ``` ## 1. The client ```ts title="lib/charchy-send.ts" import "server-only" import { CharchySend } from "@charchy/send" /** Reads CHARCHY_SEND_KEY when an email is sent, not now: `next build` never needs the key. */ export const send = new CharchySend() export const FROM = process.env.CHARCHY_SEND_FROM! // "My App " ``` ## 2. Codes, links, verification and resets ```ts title="lib/auth.ts" import { type SendEmailParams } from "@charchy/send" import { betterAuth } from "better-auth" import { emailOTP, magicLink } from "better-auth/plugins" import { after } from "next/server" import { FROM, send } from "@/lib/charchy-send" const CODE_LIFETIME_SECONDS = 5 * 60 /** Better Auth logs an error thrown here; it never reaches the person signing in. */ async function sendAuthEmail(email: Omit, idempotencyKey: string) { const { error } = await send.emails.send({ from: FROM, ...email }, { idempotencyKey }) if (error) throw error } export const auth = betterAuth({ // …your database and other options advanced: { // Send after the response, so a request's timing never shows whether an account exists. // On Vercel without Next.js, or on Cloudflare Workers: their waitUntil. backgroundTasks: { handler: (promise) => after(promise) }, }, emailAndPassword: { enabled: true, async sendResetPassword({ user, url, token }) { await sendAuthEmail( { to: user.email, subject: "Reset your password", text: `Reset your password: ${url}`, html: `

Reset your password. The link works once.

`, tags: { type: "password_reset" }, }, `password-reset/${token}` ) }, }, emailVerification: { async sendVerificationEmail({ user, url, token }) { await sendAuthEmail( { to: user.email, subject: "Confirm your email", text: `Confirm your email: ${url}`, html: `

Confirm your email

`, tags: { type: "email_verification" }, }, `verify-email/${token}` ) }, }, plugins: [ emailOTP({ expiresIn: CODE_LIFETIME_SECONDS, async sendVerificationOTP({ email, otp, type }) { // type: "sign-in" | "email-verification" | "forget-password" await sendAuthEmail( { to: email, subject: `Your code: ${otp}`, text: `Your code is ${otp}. It expires in 5 minutes.`, html: `

Your code is ${otp}. It expires in 5 minutes.

`, // A code that can't leave in time is dropped and refunded. expiresAt: new Date(Date.now() + CODE_LIFETIME_SECONDS * 1000), tags: { type: `otp_${type.replaceAll("-", "_")}` }, }, // A new code is a new email; the same code retried is not. `otp/${type}/${email}/${otp}` ) }, }), magicLink({ expiresIn: CODE_LIFETIME_SECONDS, async sendMagicLink({ email, url, token }) { await sendAuthEmail( { to: email, subject: "Your sign-in link", text: `Sign in: ${url}`, html: `

Sign in. The link works once, for 5 minutes.

`, expiresAt: new Date(Date.now() + CODE_LIFETIME_SECONDS * 1000), tags: { type: "magic_link" }, }, `magic-link/${token}` ) }, }), ], }) ``` * **Don't make the request wait on the email.** Better Auth's docs advise against awaiting the send: the time a request takes would show whether an account exists. `advanced.backgroundTasks.handler` runs these callbacks after the response — here through Next.js's `after()`; on Vercel or Cloudflare Workers without Next.js, pass their `waitUntil`. Without the option, Better Auth awaits the callback. * **Errors are logged, not shown.** Better Auth catches an error thrown in these callbacks and logs it, and the person sees the usual "check your email". Watch your logs for `error.code` (`insufficient_balance`, `domain_not_verified`, …). The SDK has already retried network errors, `5xx` and `429`. * **`expiresAt`** matches the code's lifetime (`expiresIn`, 300 seconds by default): a code that couldn't leave in time is dropped and refunded instead of arriving dead. * **Idempotency keys** come from the code or token, so a retry never sends a second email, and a new code always does. * The code in the **subject** shows in the notification, and stops Gmail from threading two codes into one conversation. ## 3. Try it With a test key in `CHARCHY_SEND_KEY`, sign in as `delivered@sim.charchy.krd`: the email shows on the dashboard's **Emails** page as delivered, with your tags. Sign in as `bounced@sim.charchy.krd` to see what happens to an address that doesn't exist — the bounce reaches your [webhook](/docs/guides/nextjs#5-webhooks-in-one-line) as `email.bounced`. --- # Supabase Auth emails > Send Supabase Auth's sign-up, magic link, recovery, invite, email change and reauthentication emails through Charchy Send with the Send Email Hook — an Edge Function, no SMTP. Source: https://charchy.krd/docs/guides/supabase Supabase Auth's **Send Email Hook** calls an HTTPS endpoint instead of sending its emails itself. Point it at an Edge Function that calls Charchy Send. ## 1. The Edge Function ```ts title="supabase/functions/send-email/index.ts" import { CharchySend, type SendEmailParams } from "npm:@charchy/send@0" import { Webhook } from "npm:standardwebhooks@1" // The hook secret is "v1,whsec_"; standardwebhooks wants the base64 part. const hook = new Webhook(Deno.env.get("SEND_EMAIL_HOOK_SECRET")!.replace("v1,whsec_", "")) // Supabase gives the whole hook 5 seconds, retries included. const send = new CharchySend(Deno.env.get("CHARCHY_SEND_KEY"), { maxRetries: 1, timeoutMs: 2_000 }) const from = Deno.env.get("CHARCHY_SEND_FROM")! const verifyUrl = `${Deno.env.get("SUPABASE_URL")}/auth/v1/verify` type HookPayload = { user: { email: string; new_email?: string } email_data: { token: string token_hash: string redirect_to: string email_action_type: string site_url: string token_new: string token_hash_new: string } } const SUBJECTS: Record = { signup: "Confirm your email", magiclink: "Your sign-in link", recovery: "Reset your password", invite: "You've been invited", email_change: "Confirm your email change", reauthentication: "Your verification code", } Deno.serve(async (request) => { const payload = await request.text() // the raw body let user: HookPayload["user"] let data: HookPayload["email_data"] try { ;({ user, email_data: data } = hook.verify(payload, Object.fromEntries(request.headers)) as HookPayload) } catch { return Response.json({ error: { http_code: 401, message: "Invalid signature" } }, { status: 401 }) } const action = data.email_action_type const subject = SUBJECTS[action] ?? "Your account was updated" const emails: { to: string; token: string; tokenHash: string }[] = // Secure email change: two emails. The names are swapped on purpose (Supabase keeps them for // backward compatibility): token_hash_new goes to the CURRENT address with token. action === "email_change" && data.token_hash_new && user.new_email ? [ { to: user.email, token: data.token, tokenHash: data.token_hash_new }, { to: user.new_email, token: data.token_new, tokenHash: data.token_hash }, ] : action === "email_change" ? [{ to: user.new_email ?? user.email, token: data.token || data.token_new, tokenHash: data.token_hash }] : [{ to: user.email, token: data.token, tokenHash: data.token_hash }] for (const email of emails) { const result = await send.emails.send( { from, to: email.to, subject, ...body(action, email.token, email.tokenHash, data.redirect_to), tags: { type: `supabase_${action}` } }, // Stable across Supabase's retries of the same hook call. { idempotencyKey: `supabase/${action}/${email.tokenHash || request.headers.get("webhook-id")}/${email.to}` } ) if (result.error) { const retry = result.error.statusCode === null || result.error.statusCode >= 500 || result.error.statusCode === 429 return Response.json( { error: { http_code: retry ? 503 : 500, message: `Charchy Send ${result.error.code}` } }, { status: retry ? 503 : 500, headers: retry ? { "retry-after": "1" } : {} } ) } } return Response.json({}) }) function body(action: string, token: string, tokenHash: string, redirectTo: string): Pick { if (!tokenHash) { // reauthentication carries a code only; *_notification types carry neither. return token ? { text: `Your code is ${token}.`, html: `

Your code is ${token}.

` } : { text: "Your account was updated. If this wasn't you, contact us.", html: "

Your account was updated. If this wasn't you, contact us.

" } } const link = `${verifyUrl}?token=${tokenHash}&type=${action}&redirect_to=${encodeURIComponent(redirectTo)}` return { text: `${SUBJECTS[action] ?? "Continue"}: ${link}\n\nOr enter this code: ${token}`, html: `

${SUBJECTS[action] ?? "Continue"}

Or enter this code: ${token}

`, } } ``` * **Signature.** Supabase signs the hook with [Standard Webhooks](https://www.standardwebhooks.com) (`webhook-id`, `webhook-timestamp`, `webhook-signature`). Its secret has a `v1,whsec_` prefix; the `standardwebhooks` library takes the base64 part after it. * **Answers.** An empty `200` means sent. `503` with `retry-after` makes Supabase retry; it gives the hook **5 seconds in all**, which is why the client gets one retry and a 2-second timeout. * **Email change.** With Secure Email Change on, one call carries two codes: `token` with `token_hash_new` for the **current** address, `token_new` with `token_hash` for the **new** one — the names are reversed in Supabase's payload. With it off, one email goes to the new address. * **Notifications.** The hook can also receive security notices (`password_changed_notification` and the other `*_notification` types). They carry no link, so the function sends a plain notice; give each its own wording if you use them. ## 2. Secrets and deploy ```bash supabase secrets set CHARCHY_SEND_KEY=chy_test_… CHARCHY_SEND_FROM="My App " supabase functions deploy send-email --no-verify-jwt ``` `--no-verify-jwt`: Supabase Auth signs the call with the hook's secret, not a user's token — the signature check protects the function. `SUPABASE_URL` is already set in every Edge Function. ## 3. Turn the hook on In the Supabase dashboard, **Authentication → Hooks**: add a **Send Email** hook of type **HTTPS** with your function's URL, and generate its secret. Set it on the function: ```bash supabase secrets set SEND_EMAIL_HOOK_SECRET="v1,whsec_…" ``` Sign up as `delivered@sim.charchy.krd` and the email shows on the Charchy dashboard's **Emails** page. --- # Laravel > Send from Laravel through Charchy Send — a small client on the Http facade, sign-in codes that expire, receipts from queued jobs, a mail transport for your Mailables and notifications, and a verified webhook route. Source: https://charchy.krd/docs/guides/laravel For Laravel 11, 12 and 13: a few small files on the `Http` facade. ## 1. Configuration ```ini title=".env" CHARCHY_SEND_KEY=chy_test_… CHARCHY_SEND_FROM="My App " CHARCHY_WEBHOOK_SECRET=whsec_… ``` ```php title="config/services.php" 'charchy_send' => [ 'key' => env('CHARCHY_SEND_KEY'), 'from' => env('CHARCHY_SEND_FROM'), 'webhook_secret' => env('CHARCHY_WEBHOOK_SECRET'), ], ``` Read them with `config('services.charchy_send.key')` — `env()` returns `null` outside config files once the config is cached. ## 2. The client ```php title="app/Services/CharchySend.php" $email The API's fields: to, subject, html and/or text; optional from, cc, bcc, reply_to, tags, attachments, scheduled_at, expires_at * * @throws RequestException refused (402, 403, 422…), or still failing after the retries * @throws ConnectionException unreachable after the retries */ public function send(array $email, string $idempotencyKey): string { return Http::withToken(config('services.charchy_send.key')) ->withHeaders(['Idempotency-Key' => $idempotencyKey]) ->acceptJson() ->timeout(30) ->retry(3, $this->retryDelay(...), $this->shouldRetry(...)) ->post('https://api.charchy.krd/v1/emails', [ 'from' => config('services.charchy_send.from'), ...$email, ]) ->json('id'); } /** Network errors, 5xx, a short 429 and 409 idempotency_in_flight. Never 402 or another 4xx. */ private function shouldRetry(Throwable $exception): bool { if ($exception instanceof ConnectionException) { return true; } if (! $exception instanceof RequestException) { return false; } $response = $exception->response; return $response->serverError() || ($response->status() === 429 && (int) $response->header('Retry-After') <= 10) || $response->json('error.code') === 'idempotency_in_flight'; } /** Retry-After when the API sends one, else 1 s, then 2 s. */ private function retryDelay(int $attempt, Throwable $exception): int { $retryAfter = $exception instanceof RequestException ? (int) $exception->response->header('Retry-After') : 0; return max($retryAfter, $attempt) * 1000; } } ``` * `retry()`'s third argument decides what is retried: network errors, `5xx`, a `429` that clears within 10 seconds, and `409 idempotency_in_flight`. Everything else — `402 insufficient_balance`, `403 domain_not_verified`, `422 validation_error` — throws a `RequestException` at once; read `$exception->response->json('error.code')`. * Every retry sends the same `Idempotency-Key`, so it can never send twice. ## 3. Sign-in codes that expire Send codes directly, not from the queue — the person is waiting: ```php use App\Services\CharchySend; app(CharchySend::class)->send([ 'to' => [$user->email], 'subject' => "Your sign-in code: {$code}", 'text' => "Your code is {$code}. It expires in 10 minutes.", 'expires_at' => now()->addMinutes(10)->toIso8601String(), // dropped and refunded if it can't leave in time 'tags' => ['type' => 'signin_code'], ], idempotencyKey: "signin-code/{$codeRow->id}"); ``` ## 4. Receipts from a queued job ```php title="app/Jobs/SendReceipt.php" send([ 'to' => [$this->order->user->email], 'subject' => "Receipt for order #{$this->order->id}", 'html' => view('mail.receipt', ['order' => $this->order])->render(), 'tags' => ['type' => 'receipt'], ], idempotencyKey: "receipt/{$this->order->id}"); } catch (RequestException $exception) { // A refusal (402, 403, 422…) won't change on a retry; a 429 or 5xx may. if ($exception->response->clientError() && $exception->response->status() !== 429) { $this->fail($exception); return; } throw $exception; } $this->order->update(['charchy_email_id' => $emailId]); } } ``` ```php SendReceipt::dispatch($order); // inside a DB::transaction too: it waits for the commit ``` * `ShouldQueueAfterCommit`: nothing is sent for an order whose transaction rolled back. * The key comes from the order, not the attempt: a job retried after a timeout gets the first email's id back instead of sending a second one. * A refusal fails the job at once; an outage or a `429` goes back on the queue with `$backoff`. ## 5. Every Mailable and notification: a mail transport Keep your Mailables, notifications and Laravel's own password-reset and verification emails — a custom transport sends them all through the API. ```php title="app/Mail/CharchySendTransport.php" getOriginalMessage()); $headers = $email->getHeaders(); $addresses = fn (array $list): array => array_map(fn (Address $address) => $address->toString(), $list); // The Envelope's `metadata` become tags: metadata: ['type' => 'order_shipped']. $tags = []; foreach ($headers->all() as $header) { if ($header instanceof MetadataHeader) { $tags[$header->getKey()] = $header->getValue(); } } $body = array_filter([ 'from' => $email->getFrom()[0]->toString(), 'to' => $addresses($email->getTo()), 'cc' => $addresses($email->getCc()), 'bcc' => $addresses($email->getBcc()), 'reply_to' => $addresses($email->getReplyTo()), 'subject' => $email->getSubject(), 'html' => $email->getHtmlBody(), 'text' => $email->getTextBody(), 'tags' => $tags, 'expires_at' => $headers->get(self::EXPIRES_AT_HEADER)?->getBodyAsString(), 'attachments' => array_map(fn (DataPart $part) => [ 'filename' => $part->getFilename(), 'content' => base64_encode($part->getBody()), 'content_type' => $part->getContentType(), ], $email->getAttachments()), ]); // Without the header: a hash of the email, so a retried queued job // sends nothing twice — and the same email to the same person within // 24 hours is sent once. $idempotencyKey = $headers->get(self::IDEMPOTENCY_KEY_HEADER)?->getBodyAsString() ?? 'laravel/'.hash('sha256', json_encode($body)); $message->setMessageId($this->client->send($body, $idempotencyKey)); } public function __toString(): string { return 'charchy'; } } ``` ```php title="app/Providers/AppServiceProvider.php" use App\Mail\CharchySendTransport; use App\Services\CharchySend; use Illuminate\Support\Facades\Mail; public function boot(): void { Mail::extend('charchy', fn () => new CharchySendTransport($this->app->make(CharchySend::class))); } ``` ```php title="config/mail.php" 'mailers' => [ 'charchy' => [ 'transport' => 'charchy', ], // … ], ``` ```ini title=".env" MAIL_MAILER=charchy MAIL_FROM_ADDRESS=no-reply@myapp.com MAIL_FROM_NAME="My App" ``` A Mailable steers the send with an `Envelope`'s `metadata` (sent as tags) and the two headers the transport reads: ```php title="app/Mail/OrderShipped.php" order->id} has shipped", metadata: ['type' => 'order_shipped'], // sent as tags ); } public function headers(): Headers { return new Headers(text: [ CharchySendTransport::IDEMPOTENCY_KEY_HEADER => "order-shipped/{$this->order->id}", ]); } public function content(): Content { return new Content(view: 'mail.order-shipped'); } } ``` | Set on the Mailable | Sent as | | ---------------------------------------- | ----------------- | | `metadata: ['type' => 'order_shipped']` | `tags` | | `X-Charchy-Idempotency-Key` header | `Idempotency-Key` | | `X-Charchy-Expires-At` header (ISO 8601) | `expires_at` | `Mail::to($user)->send(...)` returns the sent message; its `getMessageId()` is the `em_…` id. Attachments are sent (up to 3, 3 MB in all); images embedded with `$message->embed()` are not — use a [hosted image](/docs/images-and-attachments) instead. ## 6. Webhooks ```bash composer require standard-webhooks/standard-webhooks ``` ```php title="routes/web.php" use App\Http\Controllers\CharchyWebhookController; Route::post('/webhooks/charchy', CharchyWebhookController::class); ``` Charchy Send can't send a CSRF token, so take the route out of CSRF protection: ```php title="bootstrap/app.php" ->withMiddleware(function (Middleware $middleware): void { $middleware->preventRequestForgery(except: [ 'webhooks/charchy', ]); }) ``` On Laravel 11 and 12 the method is `validateCsrfTokens(except: [...])` (Laravel 13 still accepts that name). ```php title="app/Http/Controllers/CharchyWebhookController.php" verify($request->getContent(), [ // the raw body 'webhook-id' => $request->header('webhook-id'), 'webhook-timestamp' => $request->header('webhook-timestamp'), 'webhook-signature' => $request->header('webhook-signature'), ]); } catch (WebhookVerificationException) { return response('Invalid signature', 400); } HandleCharchyEvent::dispatch($event); // answer now, work later return response()->noContent(); } } ``` ```php title="app/Jobs/HandleCharchyEvent.php" $event The verified payload: id, type, created_at, data */ public function __construct(public array $event) {} public function handle(): void { $data = $this->event['data']; match ($this->event['type']) { // Idempotent, so a redelivered event changes nothing. 'email.bounced', 'email.complained' => User::where('email', $data['recipient']) ->update(['email_undeliverable_at' => now()]), default => null, }; } } ``` The controller answers `204` at once and the job does the work. Events can arrive twice and out of order: keep the handling idempotent, or record `$event['id']` and skip repeats. In the dashboard, under **Webhooks**, add `https://myapp.com/webhooks/charchy`. Without the package: [plain HMAC as middleware](/docs/webhooks#with-plain-hmac). ## 7. Try it With a test key, from `php artisan tinker`: ```php Mail::raw('It works.', fn ($message) => $message->to('delivered@sim.charchy.krd')->subject('Hello')); ``` It shows on the dashboard's **Emails** page a moment later. Send to `bounced@sim.charchy.krd` and the `email.bounced` webhook marks the user. In tests, `Http::fake(['api.charchy.krd/*' => Http::response(['id' => 'em_test', 'status' => 'queued'])])` keeps every call local. --- # Testing in CI > Run real end-to-end email tests in CI with a test key and the magic addresses — free, no inbox, no real email. Source: https://charchy.krd/docs/guides/testing-in-ci A [test key](/docs/test-mode) runs every check a live key does, then simulates delivery; the `@sim.charchy.krd` magic addresses pick the outcome. CI can test the whole email path — request, error handling, webhook — for free. ## 1. A test key in CI Create a test key (`chy_test_…`) for CI only and store it as a secret — in GitHub, **Settings → Secrets and variables → Actions**, named `CHARCHY_SEND_TEST_KEY`. ```yaml title=".github/workflows/test.yml" - name: Email tests env: CHARCHY_SEND_KEY: ${{ secrets.CHARCHY_SEND_TEST_KEY }} run: npm test -- emails ``` ## 2. A test per outcome Label each run with `+` so parallel runs don't mix, then poll `GET /v1/emails/{id}` for the status: ```ts title="emails.test.ts" import { expect, test } from "vitest" const API = "https://api.charchy.krd/v1" const headers = { Authorization: `Bearer ${process.env.CHARCHY_SEND_KEY}`, "Content-Type": "application/json", } const run = process.env.GITHUB_RUN_ID ?? "local" async function send(to: string) { const response = await fetch(`${API}/emails`, { method: "POST", headers: { ...headers, "Idempotency-Key": `ci/${run}/${to}` }, body: JSON.stringify({ from: "CI ", to, subject: "CI", text: "ok" }), }) expect(response.status).toBe(200) return (await response.json()).id as string } async function waitForStatus(id: string, wanted: string) { for (let attempt = 0; attempt < 20; attempt++) { const email = await (await fetch(`${API}/emails/${id}`, { headers })).json() if (email.status === wanted) return await new Promise((resolve) => setTimeout(resolve, 500)) } throw new Error(`${id} never reached ${wanted}`) } test("a delivered email", async () => { await waitForStatus(await send(`delivered+${run}@sim.charchy.krd`), "delivered") }) test("a bounce", async () => { await waitForStatus(await send(`bounced+${run}@sim.charchy.krd`), "bounced") }) ``` Reading emails needs a key with **full** permission. ## 3. Test your own code, not just the API Call **your** functions — the sign-up flow, the receipt job — with a magic address as the user's email, and check what your app does with the outcome: * `delivered@…` — the happy path; * `bounced@…` — does your app mark the address and ask the user to fix it? * `complained@…` — do you stop sending that user optional emails? * `suppressed@…` — does your code treat a `suppressed` status as "not sent"? * `delayed@…` — does nothing panic while an email is delayed? It turns `delivered` about 10 seconds later. Test sends don't count against your plan, credits or daily cap. Their own allowance is 1,000 recipients per rolling 24 hours per workspace, test keys and magic addresses together; past it, a send answers `429 daily_limit_reached` — keep CI from looping. ## Webhooks in CI Test-key emails fire your workspace's webhooks for real — one per recipient event. In CI, call your handler directly with a body signed by your own test secret instead of waiting for delivery; the [plain HMAC code](/docs/webhooks#with-plain-hmac) shows the signature format. --- # What counts as transactional > Charchy Send is for email a person's own action triggers. What that includes, what it doesn't, and how we check. Source: https://charchy.krd/docs/transactional **Transactional email is triggered by the recipient's own action or account** — they signed up, asked for a code, bought or booked something, or something happened to their account. They expect it and would miss it. ## Yes * Sign-in, verification and one-time codes * Password resets and security alerts * Receipts, invoices and payment confirmations * Order, shipping and delivery updates * Booking confirmations and reminders * Account notices: a plan renewing, a storage limit reached, a teammate's invite, a reply to their support ticket ## No — use Charchy Campaigns * Newsletters and product announcements * Offers, discounts and sales * "We miss you" and re-engagement emails * Anything sent to a list rather than to one person about their own action Mixing the two in one stream lets a promotion's spam complaints drag down your password resets. [Sending emails](/docs/sending-emails) has examples for the grey area. ## Why we hold the line Every sender on our delivery infrastructure shares its reputation with mail providers. Keeping the stream transactional keeps *your* password resets in the inbox, at this price. You agree to this rule in the Charchy Send terms before your first live key. ## How we check We watch for the shapes of marketing mail: * **The same email to many people.** A receipt or a code always differs (an order number, a code, a name); a promotion is identical for everyone. * **Many emails with `List-Unsubscribe`.** The header is allowed — right for product notices people can switch off — but when most of a workspace's emails carry it, they're usually a mailing list. * **Sudden blasts.** Thousands of emails in a few minutes, far above your usual pattern. * **Many `bcc` recipients** on one email — a faked mailing list. * **Spam complaints.** People complain about mail they didn't expect. ## What happens 1. If your mail looks like marketing, a person at Charchy reviews it and emails you what we saw and how to move it to Campaigns. 2. If it happens again within 30 days, or the review confirms it, API sending is **paused** (`sending_paused`) until we sort it out with you. Not sure about an email? Ask [support@charchy.krd](mailto:support@charchy.krd) before you send it. --- # Deliverability basics > How to keep your emails in the inbox — authentication and DMARC, warming up a new domain, and handling bounces and complaints. Source: https://charchy.krd/docs/deliverability Mail providers decide between inbox, spam and nowhere from **who you are** (authentication), **how you behave** (volume and history), and **how people react** (bounces and complaints). ## 1. Authenticate your domain * **DKIM** — every email is signed with your domain's key, set up once with three DNS records ([Domains and DNS](/docs/domains)). * **DMARC** — Gmail and Yahoo require one from anyone sending at volume. Start with `p=none`, read the reports for a few weeks, then move to `p=quarantine` and finally `p=reject`. A strict policy stops others from sending as your domain. ``` _dmarc.daringaming.com TXT "v=DMARC1; p=none; rua=mailto:dmarc@daringaming.com" ``` * Send from the same one or two addresses (`no-reply@`, `orders@`), so readers and filters learn to trust them. * Consider a **subdomain** (`mail.daringaming.com`) for app mail, to keep its reputation apart from your staff's everyday email. ## 2. Warm up a new domain Providers distrust a domain that suddenly sends thousands of emails, so a workspace is capped at **500 emails a day** for its first 7 days ([daily caps](/docs/rate-limits#daily-caps)). * Start with your most-wanted mail: sign-in codes, receipts. * Moving from another provider? Move a slice of your traffic first, then the rest over a week or two. ## 3. Handle bounces and complaints * A **hard bounce** (the address doesn't exist) is [suppressed](/docs/suppressions) and skipped from then on. Use the `email.bounced` webhook to ask the user to fix their address. * A **complaint** (the reader pressed "spam") suppresses the address for both the API and Campaigns, and fires `email.complained`. * Providers start filtering above about 0.1% complaints; we pause sending at 4% bounces or 0.08% complaints ([why](/docs/rate-limits#automatic-pauses)). * Only send to addresses your users gave you — never bought, scraped or guessed lists. * Confirm addresses at sign-up (a verification code does it), so typos never reach your bounce rate. ## 4. Write emails that look expected * A `from` name your users recognise, and a `subject` that says what the email is: "Your sign-in code: 482910", not "Important!". * Send a `text` part too, or let us make it from your `html`. * Keep `html` small — Gmail clips emails over about 102 KB — and use [hosted images](/docs/images-and-attachments#hosted-images) with `alt` text. * Link to your own domain, not public link shorteners (spammers use them). * For Kurdish and Arabic, set `dir="rtl"` on your HTML's container. ## Watch the numbers The dashboard's **Overview** shows delivered, bounce and complaint rates for today and the last 30 days, next to the limits that would pause sending. --- # Rate limits and quotas > Requests per second, emails per day, and the headers that tell you where you stand. Source: https://charchy.krd/docs/rate-limits Three limits, each with its own code: | Limit | How much | When you pass it | | ---------------------- | ----------------------------------------- | -------------------------- | | Requests | 10 a second per workspace, bursts of 20 | `429 rate_limit_exceeded` | | Emails a day | Your workspace's [daily cap](#daily-caps) | `429 daily_limit_reached` | | Emails you've paid for | Your plan's emails, then your credits | `402 insufficient_balance` | ## Headers | Header | When | Meaning | | ---------------------------- | ------------------------------------------------ | ----------------------------------------------------------- | | `x-request-id` | Every response | This request's id. Quote it to support. | | `ratelimit-limit` | When the request counted against your rate limit | The burst size: 20. | | `ratelimit-remaining` | When the request counted against your rate limit | Requests you can make right now. | | `ratelimit-reset` | When the request counted against your rate limit | Seconds until the burst is full again. | | `x-charchy-emails-remaining` | Sends, cancels and `GET /v1/usage` | Emails left to spend: your plan's emails plus your credits. | `429`, `409 idempotency_in_flight` and `503 sending_unavailable` carry `Retry-After`, in seconds. Wait at least that long. ## Check where you stand `GET /v1/usage` returns all of this for your workspace. Any key may call it, including a sending-only key: ```ts import { CharchySend } from "@charchy/send" const send = new CharchySend() // reads CHARCHY_SEND_KEY const { data, error } = await send.usage.get() ``` ```bash curl https://api.charchy.krd/v1/usage \ -H "Authorization: Bearer $CHARCHY_SEND_KEY" ``` ```json { "plan": { "key": "growth", "emails_included": 50000, "emails_used": 12840, "emails_left": 37160, "term_ends_at": "2026-12-14T09:00:00.000Z" }, "credits": { "emails": 25000, "expires_at": "2027-02-10T00:00:00.000Z" }, "daily": { "cap": 5000, "surge_cap": 10000, "used": 612, "resets_at": "2026-11-17T08:00:00.000Z" }, "rate_limit": { "requests_per_second": 10, "burst": 20 }, "test": { "daily_cap": 1000, "used": 37 } } ``` * `plan` is `null` without a plan term; `credits` is `null` with no credits. * `daily.cap` is the cap in force today, whichever rule below sets it. * `daily.surge_cap` is the most you can send today while healthy ([surge allowance](#daily-caps)); the same as `cap` when there is none. * `daily.resets_at` is when your count next goes down (the day is a rolling 24 hours): at `surge_cap`, when there is room for one more; under it, when the oldest counted emails leave the 24 hours. Call it from a daily health check to get alerted before `daily_limit_reached` or `insufficient_balance` happens. ## Requests per second 10 requests a second per workspace, all keys together, bursts up to 20. A [batch](/docs/batch) of 100 emails is one request. ## Daily caps A daily cap stops one mistake — a loop, a leaked key — from sending a flood. Caps count **recipients** over a **rolling 24 hours**, not a calendar day. A request that would pass the cap is refused whole, with `Retry-After` saying when there is room. | | Emails a day | | -------------------------------------------------------------- | -------------------------------- | | Before your workspace is approved (your team's addresses only) | 50 | | First 7 days after your first live email | 500 | | Starter plan | 2,500 | | Growth plan | 5,000 | | Pro plan | 10,000 | | Scale plan | 25,000 | | Credits only, no plan | 2,500 | | Test keys and magic addresses | 1,000 (free, counted separately) | **Surge allowance.** On a busy day — a launch, a sign-up rush — a plan or credits-only workspace can send up to **twice its cap** while its last 7 days stay healthy (hard bounces under 2%, spam complaints under 0.05%, or too little mail yet to judge), so your sign-in codes keep arriving. Not before approval or in the first 7 days. Every email is still paid for. `daily_limit_reached` comes at twice the cap, not at the cap. Until a workspace on **credits only** has 30 days of live sending with no automatic pause, its cap and surge are also held to about 10% of the platform's daily volume. A plan's cap is never lowered by this. An automatic pause restarts those 30 days. `GET /v1/usage` always shows the cap that applies (`daily.cap`) and the most a surge can reach (`daily.surge_cap`). We raise caps by hand for workspaces with a clean sending history — write to [support@charchy.krd](mailto:support@charchy.krd). ## Queued mail is never dropped When many emails are queued, accepted ones wait their turn: bursts slow delivery a little but never lose mail. Emails with [`expires_at`](/docs/scheduling#expires_at) go first — soonest to expire first — so set it on sign-in codes and one-time links: they overtake your receipts, which still keep moving. ## Automatic pauses Sending pauses for a workspace when: * hard **bounces** reach 4%, or **spam complaints** reach 0.08%, of its last 500 recipients (once at least 100 have gone out). Volume alone never pauses sending. When an hour jumps far above your usual, your owners and admins get an email and a notification, and for the next 24 hours the same rates are judged over your last 100 recipients (once 50 have gone out) — a leaked key mailing strangers is stopped within minutes, a sign-up rush is not. Our delivery provider can also pause a workspace's sending on its own reputation checks. Then: * new live requests answer `403 sending_paused`; * an `account.paused` webhook fires and your workspace's owners and admins get an email; * test keys keep working; * live mail already accepted is **held**, not failed. It goes out when sending resumes, unless its `expires_at` passes first or it has waited 3 days past its due time — then it is `expired` and refunded ([held mail](/docs/scheduling#held-mail)). A person resumes sending, after reviewing it with you; `account.resumed` fires then. The dashboard's **Overview** shows your bounce and complaint rates next to these limits. --- # Limits > Every size and count limit of the API in one table. Source: https://charchy.krd/docs/limits | | Limit | | -------------------- | --------------------------------------------------------------------------------------------------------- | | Recipients per email | 50 (`to` + `cc` + `bcc`, after duplicates are dropped) — a mail-server limit | | `reply_to` | 5 addresses | | Display name | 200 characters | | Emails per batch | 100, no attachments | | Request body | 5 MB — attachments are base64, a third bigger than the file | | Attachments | 3 files, 3 MB together (before base64); file name up to 255 characters. Big files belong behind a link | | Subject | 998 characters (RFC 5322) | | `html`, `text` | 512 KB each. Gmail clips an email above about 102 KB — stay well under | | Tags | 10 per email; name and value up to 256 characters each | | Custom headers | 20 per email; name up to 76 characters, value up to 998 | | `scheduled_at` | Up to 30 days ahead | | Idempotency keys | 1–256 printable ASCII characters, kept 24 hours | | Requests | 10 a second per workspace, bursts of 20 — [Rate limits](/docs/rate-limits) | | Emails a day | Your workspace's [daily cap](/docs/rate-limits#daily-caps), per recipient, rolling 24 hours | | Test sends | 1,000 recipients in a rolling 24 hours per workspace, test keys and magic addresses together | | Before approval | 50 recipients in a rolling 24 hours, your team's own addresses only | | Hosted images | 200 per workspace, 2 MB each; PNG, JPEG, GIF, WebP — [Images](/docs/images-and-attachments#hosted-images) | | `GET /v1/emails` | 1–100 per page, the last 30 days | | Email log | Emails and events 30 days, content 7 days after the email was due | | Held mail | Expired and refunded 3 days past its due time — [Scheduling](/docs/scheduling#held-mail) | | Webhook endpoints | 5 per workspace; delivery log 30 days | | API keys | 20 active per workspace (revoked keys don't count) | | Sending domains | 10 per workspace | ## Not supported * **SMTP** — HTTP API only. * **Stored templates** — render the email in your app and send the HTML. * **Receiving email** through the API. * **Open and click tracking.** * **Marketing email** — use Charchy Campaigns. See [What counts as transactional](/docs/transactional). --- # Suppressions > Addresses we stop sending to after a hard bounce or a spam complaint — why, what you see, and how to remove one. Source: https://charchy.krd/docs/suppressions Your workspace's **suppression list** holds addresses that hard-bounced or marked your mail as spam. Sending to them again hurts your domain's reputation, and with it every other email you send. ## How an address gets there | Event | Added | For | | ------------------------------------------------ | ------------- | --------------------- | | Hard bounce (`email.bounced`, `type: permanent`) | Automatically | The API and Campaigns | | Spam complaint (`email.complained`) | Automatically | The API and Campaigns | | Unsubscribe from a Campaigns newsletter | Automatically | Campaigns only | A temporary bounce (full mailbox, busy server) suppresses no one, though the email's status reads `bounced`. Simulated bounces and complaints from [magic addresses](/docs/test-mode#magic-addresses) never touch the list. ## What happens when you send to one * Suppressed recipients are **skipped** and **not charged**; the other recipients get the email as usual. * Each skipped recipient gets a `suppressed` event on the timeline and its own `email.suppressed` webhook, with `data.recipient` and `reason` `previous_bounce` or `previous_complaint` ([Events](/docs/events)). * If **every** recipient is suppressed, the request still succeeds with `200` and the email's status is `suppressed`. * The check runs when you send the request, with test keys too. ## Unsubscribed is not suppressed The API never skips an address only because it unsubscribed from Campaigns — that person still needs their password resets and receipts. Only bounces and complaints count. ## Removing an address **Suppressions** in the dashboard lists each address with why and when it was added. A teammate who manages sending can let a **bounced** address back: * **Bounces only.** A spam complaint stays on the list — mailing someone who reported you is the fastest way to lose your sending. An unsubscribe can't be taken back either. * **Once per address.** If it bounces again, it stays; write to [support@charchy.krd](mailto:support@charchy.krd) if the mailbox really works now. * **Up to 20 a day** per workspace — bulk clearing is how senders end up mailing dead addresses. Let an address back only when the problem is fixed — the person corrected a typo, or asked for your emails again. An address that still doesn't exist only earns a second bounce. ## In your app On `email.bounced` and `email.complained`, mark the address in your own database and ask the user to update it at their next sign-in. --- # Troubleshooting > The common problems and their fixes — a domain that won't verify, domain_not_verified, emails delivered but not received, and keys used from the browser. Source: https://charchy.krd/docs/troubleshooting ## My domain won't verify **Domains** in the dashboard shows each record's status and keeps checking. * **Wait.** New records usually appear within minutes; some DNS providers take an hour or more. * **The domain written twice.** Many DNS panels append your domain to every name, so a pasted full name lands at `abc123._domainkey.yourdomain.com.yourdomain.com`. Enter only `abc123._domainkey`. Your provider's page shows how: [Cloudflare](/docs/domains/cloudflare) · [Hostinger](/docs/domains/hostinger) · [GoDaddy](/docs/domains/godaddy) · [Namecheap](/docs/domains/namecheap) · [Route 53](/docs/domains/route-53). * **The Cloudflare proxy is on.** DKIM records must be **DNS only** (grey cloud), never **Proxied**. * **You edited the wrong place.** Records only count where your domain's **nameservers** point — if DNS is hosted somewhere other than your registrar (Cloudflare, your web host), add them there. `dig NS yourdomain.com` shows where. * **A typo in the value.** Use the copy button; one missing character breaks the record. Check a record yourself: ```bash dig CNAME abc123._domainkey.yourdomain.com +short dig TXT _dmarc.yourdomain.com +short ``` ## The API says `domain_not_verified` or `sender_not_allowed` * `domain_not_verified`: the domain is in this workspace but not verified. Finish its records in **Domains** (see above). If verification gave up after 72 hours, or a verified domain lost its records, you also got a `domain.failed` webhook. * `sender_not_allowed`: the `from` domain isn't in this workspace. Check for a typo, and that you're using this workspace's key. * Sending from a subdomain (`mail.yourdomain.com`)? The subdomain itself must be the verified domain. * Worked before, now emails end `failed` with `reason` `domain_not_verified`? Someone changed the DNS — put the records back; the domain comes back by itself within hours. Those emails are refunded. * Just testing? A [test key](/docs/test-mode) may send from any domain. ## Delivered, but it never arrived `delivered` means the recipient's mail server accepted the email; what happens next is that provider's choice. * **Look in spam and promotions.** If it's there, your domain is new or unauthenticated: set up [DMARC](/docs/domains#the-dmarc-record) and [warm up](/docs/deliverability#2-warm-up-a-new-domain). * **Company mail servers** sometimes quarantine mail from new senders. Ask the recipient's IT team to check. * **Gmail cut the email off.** Gmail clips emails over about 102 KB behind a "\[Message clipped]" link. Keep the HTML small and use [hosted images](/docs/images-and-attachments#hosted-images). * **Gmail joined two emails into one thread.** Two sign-in codes with the same subject can collapse into one conversation. Put the code in the subject, or add a unique `X-Entity-Ref-ID` [header](/docs/tags-and-headers#headers). * Still nothing? Open the email in **Emails** and send its id to [support@charchy.krd](mailto:support@charchy.krd) — we can see the receiving server's answer. ## It says `suppressed` The address hard-bounced or complained before, so we skipped it and didn't charge. [Suppressions](/docs/suppressions) explains when you can let a bounced address back. ## It says `unknown` The email was handed over, but no answer or delivery event came back within 30 minutes. It may have left, so we never send it again, and the charge stays. A later event can still settle it; if it stays `unknown`, send its id to [support@charchy.krd](mailto:support@charchy.krd). ## "CORS" errors, or a key used from the browser The API sends no CORS headers, so a `fetch` from a web page fails — on purpose: a key in browser code is a key anyone can copy. Move the call to your server (an API route, a server action, your backend), reading the key from its environment. If the key has already shipped in browser code, [revoke it](/docs/api-keys#if-a-key-leaks). ## `401 invalid_api_key` in production only * The production environment doesn't have `CHARCHY_SEND_KEY` set, or still has an old value after a key was revoked. * The value is cut off or has extra characters: a key is `chy_live_` or `chy_test_` followed by 64 characters. * Your host needs a redeploy before new environment variables apply. ## `403 not_approved` Before approval, a live key sends only to your own team, up to 50 recipients a day. Use magic addresses or a test key meanwhile, and write to [support@charchy.krd](mailto:support@charchy.krd) to finish approval. --- # API reference > Every endpoint, field and response of the Charchy Send API, generated from our OpenAPI file. Source: https://charchy.krd/docs/api-reference These pages are generated from the OpenAPI file the API is built against. Download it for code generators, API clients and AI agents: **[charchy.krd/docs/openapi.yaml](https://charchy.krd/docs/openapi.yaml)** (OpenAPI 3.1) ## Basics | | | | -------------- | ------------------------------------------------------------------------------------- | | Base URL | `https://api.charchy.krd/v1` | | Authentication | `Authorization: Bearer chy_live_…` or `chy_test_…` | | Request bodies | JSON (`Content-Type: application/json`), except image uploads (`multipart/form-data`) | | Times | ISO 8601 strings, e.g. `2026-11-20T09:00:00+03:00` | | Ids | Emails `em_…`, images `img_…`, webhook events `evt_…` | | Addresses | `to`, `cc`, `bcc` and `reply_to` take one address or an array | | Errors | `{ "error": { "code", "message", "field"?, "docs" } }` — [all codes](/docs/errors) | | Duplicates | [`Idempotency-Key`](/docs/idempotency) header on every send | | Limits | [Rate limits](/docs/rate-limits), [sizes and counts](/docs/limits) | ## Endpoints | | | | -------------------------- | ------------------------------------------------------------------------------------------------------------ | | `POST /emails` | [Send an email](/docs/send-email) | | `POST /emails/batch` | [Send up to 100 emails](/docs/batch) | | `GET /emails/{id}` | An email's status and event timeline | | `GET /emails` | List emails of the last 30 days | | `PATCH /emails/{id}` | [Reschedule](/docs/scheduling#change-the-time) a scheduled email | | `POST /emails/{id}/cancel` | [Cancel](/docs/scheduling#cancel) a scheduled or queued email | | `POST /images` | [Host an image](/docs/images-and-attachments#hosted-images) for your emails | | `GET /usage` | Your plan, credits, daily cap and limits — [Rate limits and quotas](/docs/rate-limits#check-where-you-stand) | [Webhooks](/docs/webhooks) are described in the same file, under `webhooks`. There is no "try it" console: the API sends no CORS headers, because a key belongs on a server. Use curl or your own code with a [test key](/docs/test-mode). --- # Send an email > Accepts one email and queues it (or schedules it, with `scheduled_at`). The answer comes back at once; delivery is reported by webhooks and `GET /emails/{id}`. Charged per recipient when accepted, refunded if the email is canceled, expires, is suppressed or fails for good. Source: https://charchy.krd/docs/api-reference/send-email `POST https://api.charchy.krd/v1/emails` ```yaml /emails: post: tags: - Emails operationId: sendEmail summary: Send an email description: | Accepts one email and queues it (or schedules it, with `scheduled_at`). The answer comes back at once; delivery is reported by webhooks and `GET /emails/{id}`. Charged per recipient when accepted, refunded if the email is canceled, expires, is suppressed or fails for good. parameters: - $ref: "#/components/parameters/IdempotencyKey" requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/SendEmailRequest" examples: order: summary: An order confirmation value: from: Darin Game to: - customer@example.com reply_to: support@daringaming.com subject: "Your order #4821" html:

Thanks for your order!

tags: type: order_confirmation signInCode: summary: A sign-in code that expires value: from: My App to: - user@example.com subject: "Your sign-in code: 482910" text: Your code is 482910. It expires in 10 minutes. expires_at: 2026-11-16T12:10:00Z responses: "200": description: Accepted. headers: ratelimit-limit: $ref: "#/components/headers/RateLimitLimit" ratelimit-remaining: $ref: "#/components/headers/RateLimitRemaining" ratelimit-reset: $ref: "#/components/headers/RateLimitReset" x-charchy-emails-remaining: $ref: "#/components/headers/EmailsRemaining" content: application/json: schema: $ref: "#/components/schemas/AcceptedEmail" example: id: em_8f2k1x9q4w7m3n5p6r0s2t4v status: queued "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "402": $ref: "#/components/responses/InsufficientBalance" "403": $ref: "#/components/responses/SendForbidden" "409": $ref: "#/components/responses/IdempotencyConflict" "413": $ref: "#/components/responses/PayloadTooLarge" "422": $ref: "#/components/responses/Unprocessable" "429": $ref: "#/components/responses/TooManyRequests" "500": $ref: "#/components/responses/InternalError" "503": $ref: "#/components/responses/SendingUnavailable" ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # Send a batch > Up to 100 emails in one request, without attachments. Validation is all-or-nothing: one invalid email and nothing is sent, with every problem listed by index. Charged once for the whole batch. Source: https://charchy.krd/docs/api-reference/send-email-batch `POST https://api.charchy.krd/v1/emails/batch` ```yaml /emails/batch: post: tags: - Emails operationId: sendEmailBatch summary: Send a batch description: | Up to 100 emails in one request, without attachments. Validation is all-or-nothing: one invalid email and nothing is sent, with every problem listed by index. Charged once for the whole batch. parameters: - $ref: "#/components/parameters/IdempotencyKey" requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/BatchRequest" responses: "200": description: Every email accepted. Ids are in request order. headers: ratelimit-limit: $ref: "#/components/headers/RateLimitLimit" ratelimit-remaining: $ref: "#/components/headers/RateLimitRemaining" ratelimit-reset: $ref: "#/components/headers/RateLimitReset" x-charchy-emails-remaining: $ref: "#/components/headers/EmailsRemaining" content: application/json: schema: $ref: "#/components/schemas/BatchResponse" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "402": $ref: "#/components/responses/InsufficientBalance" "403": $ref: "#/components/responses/SendForbidden" "409": $ref: "#/components/responses/IdempotencyConflict" "413": $ref: "#/components/responses/PayloadTooLarge" "422": description: At least one email is invalid. Nothing was sent. content: application/json: schema: $ref: "#/components/schemas/BatchValidationError" "429": $ref: "#/components/responses/TooManyRequests" "500": $ref: "#/components/responses/InternalError" "503": $ref: "#/components/responses/SendingUnavailable" ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # Get an email > An email's status, recipients, tags, timestamps and event timeline. Kept for 30 days. Needs a key with full permission. Source: https://charchy.krd/docs/api-reference/get-email `GET https://api.charchy.krd/v1/emails/{id}` ```yaml /emails/{id}: get: tags: - Emails operationId: getEmail summary: Get an email description: | An email's status, recipients, tags, timestamps and event timeline. Kept for 30 days. Needs a key with full permission. responses: "200": description: The email. content: application/json: schema: $ref: "#/components/schemas/Email" "401": $ref: "#/components/responses/Unauthorized" "403": $ref: "#/components/responses/RestrictedKey" "404": $ref: "#/components/responses/NotFound" "429": $ref: "#/components/responses/TooManyRequests" "500": $ref: "#/components/responses/InternalError" ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # List emails > Your workspace's emails of the last 30 days, newest first, with cursor pagination. Needs a key with full permission. Source: https://charchy.krd/docs/api-reference/list-emails `GET https://api.charchy.krd/v1/emails` ```yaml /emails: get: tags: - Emails operationId: listEmails summary: List emails description: | Your workspace's emails of the last 30 days, newest first, with cursor pagination. Needs a key with full permission. parameters: - name: limit in: query description: Page size, 1–100. schema: type: integer minimum: 1 maximum: 100 default: 20 - name: after in: query description: The `next_cursor` of the previous page. schema: type: string - name: status in: query schema: $ref: "#/components/schemas/EmailStatus" - name: tag in: query description: A tag as `key:value`, e.g. `type:order_confirmation`. schema: type: string - name: to in: query description: A recipient address. schema: type: string format: email responses: "200": description: A page of emails. headers: ratelimit-limit: $ref: "#/components/headers/RateLimitLimit" ratelimit-remaining: $ref: "#/components/headers/RateLimitRemaining" ratelimit-reset: $ref: "#/components/headers/RateLimitReset" content: application/json: schema: $ref: "#/components/schemas/EmailList" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "403": $ref: "#/components/responses/RestrictedKey" "429": $ref: "#/components/responses/TooManyRequests" "500": $ref: "#/components/responses/InternalError" ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # Reschedule an email > Changes `scheduled_at` while the email is still `scheduled`. Source: https://charchy.krd/docs/api-reference/reschedule-email `PATCH https://api.charchy.krd/v1/emails/{id}` ```yaml /emails/{id}: patch: tags: - Emails operationId: rescheduleEmail summary: Reschedule an email description: Changes `scheduled_at` while the email is still `scheduled`. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/RescheduleRequest" responses: "200": description: Rescheduled. content: application/json: schema: $ref: "#/components/schemas/RescheduledEmail" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "403": $ref: "#/components/responses/RestrictedKey" "404": $ref: "#/components/responses/NotFound" "422": $ref: "#/components/responses/Unprocessable" "429": $ref: "#/components/responses/TooManyRequests" "500": $ref: "#/components/responses/InternalError" ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # Cancel an email > Cancels an email that is `scheduled` or `queued`. It is refunded and fires `email.canceled`. Source: https://charchy.krd/docs/api-reference/cancel-email `POST https://api.charchy.krd/v1/emails/{id}/cancel` ```yaml /emails/{id}/cancel: post: tags: - Emails operationId: cancelEmail summary: Cancel an email description: | Cancels an email that is `scheduled` or `queued`. It is refunded and fires `email.canceled`. responses: "200": description: Canceled. content: application/json: schema: $ref: "#/components/schemas/AcceptedEmail" example: id: em_5k2m8x1q9w3r3n5p6r0s2t4v status: canceled "401": $ref: "#/components/responses/Unauthorized" "403": $ref: "#/components/responses/RestrictedKey" "404": $ref: "#/components/responses/NotFound" "429": $ref: "#/components/responses/TooManyRequests" "500": $ref: "#/components/responses/InternalError" ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # Upload an image > Hosts an image on files.charchy.krd and returns its permanent public URL, for `` in your emails. PNG, JPEG, GIF or WebP (no SVG), up to 2 MB, up to 200 per workspace. Source: https://charchy.krd/docs/api-reference/upload-image `POST https://api.charchy.krd/v1/images` ```yaml /images: post: tags: - Images operationId: uploadImage summary: Upload an image description: | Hosts an image on files.charchy.krd and returns its permanent public URL, for `` in your emails. PNG, JPEG, GIF or WebP (no SVG), up to 2 MB, up to 200 per workspace. requestBody: required: true content: multipart/form-data: schema: type: object required: - file properties: file: type: string format: binary description: The image file. responses: "200": description: Uploaded. content: application/json: schema: $ref: "#/components/schemas/Image" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "403": $ref: "#/components/responses/RestrictedKey" "413": $ref: "#/components/responses/PayloadTooLarge" "429": $ref: "#/components/responses/TooManyRequests" "500": $ref: "#/components/responses/InternalError" ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # Get usage > Where your workspace stands: this term's plan emails, your credits and their expiry, today's cap, the rate limit, and today's test sends. Needs a key with full permission. Source: https://charchy.krd/docs/api-reference/get-usage `GET https://api.charchy.krd/v1/usage` ```yaml /usage: get: tags: - Usage operationId: getUsage summary: Get usage description: | Where your workspace stands: this term's plan emails, your credits and their expiry, today's cap, the rate limit, and today's test sends. Needs a key with full permission. responses: "200": description: Your usage right now. content: application/json: schema: $ref: "#/components/schemas/Usage" "401": $ref: "#/components/responses/Unauthorized" "403": $ref: "#/components/responses/RestrictedKey" "429": $ref: "#/components/responses/TooManyRequests" "500": $ref: "#/components/responses/InternalError" ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # Email events > Sent to your endpoint when an email changes state. `type` is one of `email.sent`, `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained`, `email.failed`, `email.suppressed`, `email.expired`, `email.canceled`. One event per recipient for `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained` and `email.suppressed` — `data.recipient` names the address. `email.sent`, `email.failed`, `email.expired` and `email.canceled` come once per email. Emails sent with a test key, and the magic addresses, fire these events too. Signed with the Standard Webhooks spec: verify `webhook-signature` against the raw body, reject timestamps older than 5 minutes, and dedupe by `webhook-id`. Order is not guaranteed. Answer 2xx within 5 seconds; `410 Gone` disables the endpoint. Requests carry `user-agent: Charchy-Webhooks/1.0 (+https://charchy.krd/docs/webhooks)`. Source: https://charchy.krd/docs/api-reference/email-event Webhook `email-event` — sent as `POST` to your endpoint. ```yaml email-event: post: operationId: emailEvent summary: Email events description: | Sent to your endpoint when an email changes state. `type` is one of `email.sent`, `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained`, `email.failed`, `email.suppressed`, `email.expired`, `email.canceled`. One event per recipient for `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained` and `email.suppressed` — `data.recipient` names the address. `email.sent`, `email.failed`, `email.expired` and `email.canceled` come once per email. Emails sent with a test key, and the magic addresses, fire these events too. Signed with the Standard Webhooks spec: verify `webhook-signature` against the raw body, reject timestamps older than 5 minutes, and dedupe by `webhook-id`. Order is not guaranteed. Answer 2xx within 5 seconds; `410 Gone` disables the endpoint. Requests carry `user-agent: Charchy-Webhooks/1.0 (+https://charchy.krd/docs/webhooks)`. parameters: - $ref: "#/components/parameters/WebhookId" - $ref: "#/components/parameters/WebhookTimestamp" - $ref: "#/components/parameters/WebhookSignature" requestBody: content: application/json: schema: $ref: "#/components/schemas/EmailWebhookEvent" responses: 2XX: description: Received. Do the work after answering. ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # Domain events > `domain.verified` when a sending domain is verified and ready to send from (again, too, once a domain that lost its records has them back); `domain.failed` when its verification fails — the DKIM records weren't found within 72 hours, or setting the domain up failed — or when a verified domain's records are gone at two daily re-checks a few hours apart. Signed like every event. Source: https://charchy.krd/docs/api-reference/domain-event Webhook `domain-event` — sent as `POST` to your endpoint. ```yaml domain-event: post: operationId: domainEvent summary: Domain events description: | `domain.verified` when a sending domain is verified and ready to send from (again, too, once a domain that lost its records has them back); `domain.failed` when its verification fails — the DKIM records weren't found within 72 hours, or setting the domain up failed — or when a verified domain's records are gone at two daily re-checks a few hours apart. Signed like every event. parameters: - $ref: "#/components/parameters/WebhookId" - $ref: "#/components/parameters/WebhookTimestamp" - $ref: "#/components/parameters/WebhookSignature" requestBody: content: application/json: schema: $ref: "#/components/schemas/DomainWebhookEvent" responses: 2XX: description: Received. ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # Account events > `account.paused` when sending is paused for your workspace (whoever paused it), `account.resumed` when it resumes, and `balance.low` when what you have left falls to 20% of what you had after your last top-up (`used_percent: 80`) and when it reaches zero (`100`) — once each per top-up. A top-up is a plan term starting, or credits added. Signed like every event. Source: https://charchy.krd/docs/api-reference/account-event Webhook `account-event` — sent as `POST` to your endpoint. ```yaml account-event: post: operationId: accountEvent summary: Account events description: | `account.paused` when sending is paused for your workspace (whoever paused it), `account.resumed` when it resumes, and `balance.low` when what you have left falls to 20% of what you had after your last top-up (`used_percent: 80`) and when it reaches zero (`100`) — once each per top-up. A top-up is a plan term starting, or credits added. Signed like every event. parameters: - $ref: "#/components/parameters/WebhookId" - $ref: "#/components/parameters/WebhookTimestamp" - $ref: "#/components/parameters/WebhookSignature" requestBody: content: application/json: schema: $ref: "#/components/schemas/AccountWebhookEvent" responses: 2XX: description: Received. ``` The `$ref`s above point into the full OpenAPI file: https://charchy.krd/docs/openapi.yaml --- # Errors > Every error code the API returns, what it means, and whether to retry. Each error's docs link points here. Source: https://charchy.krd/docs/errors Every error has this shape. `docs` links to the code's section on this page; `field` names the field at fault, when there is one. Every response carries an `x-request-id` header: quote it to support. ```json { "error": { "code": "domain_not_verified", "message": "daringaming.com is not verified in this workspace.", "docs": "https://charchy.krd/docs/errors#domain_not_verified" } } ``` Match on `code`, never on `message`: messages can change, codes never do. ## All codes | HTTP | Code | Retry? | | ---- | ----------------------------------------------------- | ------------------------ | | 400 | [`invalid_json`](#invalid_json) | No | | 400 | [`validation_error`](#validation_error) | No | | 400 | [`invalid_idempotency_key`](#invalid_idempotency_key) | No | | 401 | [`missing_api_key`](#missing_api_key) | No | | 401 | [`invalid_api_key`](#invalid_api_key) | No | | 402 | [`insufficient_balance`](#insufficient_balance) | **No** | | 403 | [`restricted_api_key`](#restricted_api_key) | No | | 403 | [`domain_not_verified`](#domain_not_verified) | No | | 403 | [`sender_not_allowed`](#sender_not_allowed) | No | | 403 | [`not_approved`](#not_approved) | No | | 403 | [`sending_paused`](#sending_paused) | No | | 404 | [`not_found`](#not_found) | No | | 409 | [`idempotency_conflict`](#idempotency_conflict) | No | | 409 | [`idempotency_in_flight`](#idempotency_in_flight) | Yes, after `Retry-After` | | 413 | [`payload_too_large`](#payload_too_large) | No | | 422 | [`invalid_attachment`](#invalid_attachment) | No | | 422 | [`too_many_recipients`](#too_many_recipients) | No | | 422 | [`schedule_out_of_range`](#schedule_out_of_range) | No | | 429 | [`rate_limit_exceeded`](#rate_limit_exceeded) | Yes, after `Retry-After` | | 429 | [`daily_limit_reached`](#daily_limit_reached) | Yes, after `Retry-After` | | 500 | [`internal_error`](#internal_error) | Yes, with backoff | | 503 | [`sending_unavailable`](#sending_unavailable) | Yes, after `Retry-After` | Retrying is only safe with an [`Idempotency-Key`](/docs/idempotency) — send one on every request. ## 400 Bad Request ### `invalid_json` The body isn't valid JSON, or isn't a JSON object. Send `Content-Type: application/json` and serialise the body once — a JSON string inside a JSON string is the usual cause. ### `validation_error` A field is missing or wrong. `field` names it; `message` says what's wrong — an address that isn't one, an unknown field, a reserved header, a line break in a subject, a `scheduled_at` without a time zone, an `expires_at` already past. In a [batch](/docs/batch), invalid emails answer `422`, and `items` lists every problem by the email's index, each with its own `code`. Also returned for well-formed requests that can't be done: rescheduling an email that isn't `scheduled`, canceling one that has already left, uploading an image that isn't PNG, JPEG, GIF or WebP, or a 201st hosted image. ```json { "error": { "code": "validation_error", "field": "to", "message": "\"ara@\" is not an email address.", "docs": "https://charchy.krd/docs/errors#validation_error" } } ``` ### `invalid_idempotency_key` The `Idempotency-Key` header is empty, longer than 256 characters, or has anything other than printable ASCII — a line break, a tab, a Kurdish or Arabic letter. Nothing was sent. Use a short key made from the event, like `password-reset/7f1c2a`. See [Idempotency](/docs/idempotency). ## 401 Unauthorized ### `missing_api_key` No `Authorization` header at all. Send `Authorization: Bearer `. ### `invalid_api_key` The key is unknown, revoked (effective at once), not shaped like a Charchy Send key (or not sent as `Bearer `), or its workspace no longer has Charchy Send. Check you're reading the right environment variable and that it holds the whole key. ## 402 Payment Required ### `insufficient_balance` Your plan's emails for this term **and** your credits don't cover this request — counted per recipient, all or nothing. Buy credits or renew your plan in **Usage & billing**, then send again with the same `Idempotency-Key` (a refused request isn't remembered under it). **Don't retry automatically** — nothing changes until someone pays. Alert a person instead. A [`balance.low`](/docs/webhooks#events) webhook at 80% warns you first. ## 403 Forbidden ### `restricted_api_key` The key isn't allowed to do this: * a **sending-only** key read, listed, rescheduled or canceled an email, or uploaded an image (it may send and call `GET /v1/usage`); * a key **locked to one domain** sent from another; * a locked key's domain was removed from the workspace, so it can't send at all — make a new key. Use a key with full permission, or the right domain. ### `domain_not_verified` The `from` domain is added to this workspace but not verified — its DNS records aren't published, or verification gave up. Open **Domains** in the dashboard; see [Domains and DNS](/docs/domains). A [test key](/docs/test-mode) may send from any domain meanwhile. ### `sender_not_allowed` The `from` domain isn't one of this workspace's sending domains — never added here, or a typo. Only the exact domain counts: add a subdomain on its own. Add and verify it under **Domains**. ### `not_approved` Your workspace isn't approved for live sending yet, so a live key sends only to your own team's addresses (up to 50 recipients a day). `field` names the first address that isn't one. Use a [test key or a magic address](/docs/test-mode), or contact us to finish approval. ### `sending_paused` Live sending is paused for your workspace — usually because bounces or spam complaints rose too high, volume jumped far above normal, or mail looked like marketing ([why](/docs/transactional), [automatic pauses](/docs/rate-limits#automatic-pauses)). Your owners and admins got an email with the reason, and an `account.paused` webhook fired. Test keys keep working. Live mail accepted before the pause is held: it goes out when sending resumes, unless its `expires_at` passes or it waits 3 days past its due time first ([held mail](/docs/scheduling#held-mail)). Retrying doesn't help; sending resumes once we've reviewed it with you. ## 404 Not Found ### `not_found` No email with this id in your workspace — including ids from another workspace, anything not shaped like an email id (`em_` and 24 letters and digits), and emails older than 30 days. ## 409 Conflict ### `idempotency_conflict` You reused an `Idempotency-Key` from the last 24 hours with a **different body**, or on the other send endpoint (`/v1/emails` and `/v1/emails/batch` share keys). Nothing was sent. Make the key from the event that causes the email, so different emails never share one. See [Idempotency](/docs/idempotency). ### `idempotency_in_flight` A request with the same `Idempotency-Key` is still being processed — this happens while a request with attachments or a large body uploads. Wait `Retry-After` seconds and retry with the same key: you get the first request's answer. ## 413 Content Too Large ### `payload_too_large` The request body is over 5 MB, `html` or `text` is over 512 KB, or a hosted image is over 2 MB. Put large files behind a download link, and big images in [hosted images](/docs/images-and-attachments#hosted-images). ## 422 Unprocessable Content ### `invalid_attachment` An attachment is invalid: `filename` or `content_type` is missing, `content` isn't valid base64 or is an empty file, there are more than 3 files or more than 3 MB together, its type is blocked (executables and scripts), or a `content_id` is used twice. See [attachments](/docs/images-and-attachments#attachments). (Attachments in a [batch](/docs/batch) answer `validation_error`.) ### `too_many_recipients` `to`, `cc` and `bcc` together have more than 50 addresses, after duplicates are dropped. Send one email per person instead. ### `schedule_out_of_range` `scheduled_at` is more than 30 days ahead, when sending or when rescheduling. See [Scheduling](/docs/scheduling). ## 429 Too Many Requests ### `rate_limit_exceeded` More than 10 requests a second from your workspace, all keys together (bursts of 20 are allowed). Wait `Retry-After` seconds and retry. Sending many at once? Use [batch](/docs/batch). See [Rate limits](/docs/rate-limits). ### `daily_limit_reached` This request would take your workspace past its daily cap — or, while your sending is healthy, past twice it (the surge allowance) — counted per recipient over a rolling 24 hours. Nothing was sent. Also returned when test keys and magic addresses pass their 1,000 a day, and when a live key passes 50 a day before approval. `Retry-After` says when there is room. Caps grow with your plan and sending history — see [Rate limits and quotas](/docs/rate-limits#daily-caps). ## 500 and 503 ### `internal_error` Something broke on our side. Retry with backoff and the same `Idempotency-Key`. If it persists, write to [support@charchy.krd](mailto:support@charchy.krd) with the time and the email's details. ### `sending_unavailable` Live sending is halted on our side, for every workspace, for 10 minutes or more. Your request was not accepted or charged; wait `Retry-After` seconds and retry with the same `Idempotency-Key`. Test keys keep working. Live mail accepted before the halt is held and goes out when sending comes back. --- # Changelog > Changes to the Charchy Send API and these docs, newest first. Source: https://charchy.krd/docs/changelog Within `v1` we never rename an error code or remove a field. New fields and events may appear at any time — ignore fields your code doesn't know. ## November 17, 2026 — Guides * New guides: [Next.js](/docs/guides/nextjs), [Convex](/docs/guides/convex), and [Vercel](/docs/domains/vercel) under Domains & DNS. * [Better Auth](/docs/guides/better-auth), [Supabase](/docs/guides/supabase) and [Laravel](/docs/guides/laravel) rewritten for their current versions and the SDK; webhook examples in Laravel. ## November 2026 — `@charchy/send` 0.1.0 The [Node.js and TypeScript SDK](/docs/sdks/node): every endpoint, retries that never send twice, and webhook verification. ## November 2026 — v1, invite-only The first version of the API. * `POST /v1/emails`, `POST /v1/emails/batch` (up to 100 emails). * `GET /v1/emails/{id}`, `GET /v1/emails`, `PATCH /v1/emails/{id}`, `POST /v1/emails/{id}/cancel`. * `POST /v1/images` for hosted images, and `GET /v1/usage` for your plan, credits, daily cap and limits. * `to`, `cc`, `bcc` and `reply_to` take one address or an array; `tags` take an object or an array of `{ name, value }` pairs. * `List-Unsubscribe` and `List-Unsubscribe-Post` allowed as custom headers. * `scheduled_at` up to 30 days ahead, and `expires_at` for time-sensitive emails. * `Idempotency-Key` on every endpoint that sends (`400 invalid_idempotency_key` for a malformed one). * Test keys and the `@sim.charchy.krd` magic addresses. * Webhooks signed with the Standard Webhooks spec. * Docs at charchy.krd/docs, with `llms.txt`, a Markdown copy of every page, and an OpenAPI file. ## Coming next * `/v1/domains`, `/v1/webhooks` and `/v1/suppressions`, so you can set up a workspace without the dashboard. --- # OpenAPI file Source: https://charchy.krd/docs/openapi.yaml ```yaml # Charchy Send (Namabar) — the public contract of the Email API, v1. # # Written by hand, next to the code that serves it. The developer docs render # it at https://charchy.krd/docs/api-reference and serve it raw, exactly as # written (comments included — keep them fit to publish), at # https://charchy.krd/docs/openapi.yaml. # # Change this file in the same commit as the behaviour it describes. Error # codes and field names are published to developers: never rename one. # # The public SDK (github.com/charchyy/charchy-send) generates its types from # this file as published at charchy.krd/docs/openapi.yaml — keep changes # additive. openapi: 3.1.0 info: title: Charchy Send API version: "1.0.0" summary: Transactional email for your app, sent from your own domain. description: | Send transactional email — sign-in codes, password resets, receipts, order and booking updates — from your own verified domain. Every request is authenticated with an API key in the `Authorization` header. Test keys (`chy_test_…`) go through every check but never send; live keys (`chy_live_…`) send real mail. Keys belong on your server: the API sends no CORS headers. Every error answers `{ "error": { "code", "message", "docs" } }`, and `docs` links to the code's section of https://charchy.krd/docs/errors. contact: name: Charchy support email: support@charchy.krd url: https://charchy.krd/docs servers: - url: https://api.charchy.krd/v1 description: Production security: - apiKey: [] tags: - name: Emails description: Send emails, read their status, reschedule or cancel them. - name: Images description: Host images for your emails on files.charchy.krd. - name: Usage description: Your plan, credits, caps and limits. paths: /emails: post: tags: [Emails] operationId: sendEmail summary: Send an email description: | Accepts one email and queues it (or schedules it, with `scheduled_at`). The answer comes back at once; delivery is reported by webhooks and `GET /emails/{id}`. Charged per recipient when accepted, refunded if the email is canceled, expires, is suppressed or fails for good. parameters: - $ref: "#/components/parameters/IdempotencyKey" requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/SendEmailRequest" examples: order: summary: An order confirmation value: from: Darin Game to: [customer@example.com] reply_to: support@daringaming.com subject: "Your order #4821" html:

Thanks for your order!

tags: type: order_confirmation signInCode: summary: A sign-in code that expires value: from: My App to: [user@example.com] subject: "Your sign-in code: 482910" text: Your code is 482910. It expires in 10 minutes. expires_at: "2026-11-16T12:10:00Z" responses: "200": description: Accepted. headers: ratelimit-limit: { $ref: "#/components/headers/RateLimitLimit" } ratelimit-remaining: { $ref: "#/components/headers/RateLimitRemaining" } ratelimit-reset: { $ref: "#/components/headers/RateLimitReset" } x-charchy-emails-remaining: { $ref: "#/components/headers/EmailsRemaining" } content: application/json: schema: $ref: "#/components/schemas/AcceptedEmail" example: id: em_8f2k1x9q4w7m3n5p6r0s2t4v status: queued "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "402": { $ref: "#/components/responses/InsufficientBalance" } "403": { $ref: "#/components/responses/SendForbidden" } "409": { $ref: "#/components/responses/IdempotencyConflict" } "413": { $ref: "#/components/responses/PayloadTooLarge" } "422": { $ref: "#/components/responses/Unprocessable" } "429": { $ref: "#/components/responses/TooManyRequests" } "500": { $ref: "#/components/responses/InternalError" } "503": { $ref: "#/components/responses/SendingUnavailable" } get: tags: [Emails] operationId: listEmails summary: List emails description: | Your workspace's emails of the last 30 days, newest first, with cursor pagination. Needs a key with full permission. parameters: - name: limit in: query description: Page size, 1–100. schema: { type: integer, minimum: 1, maximum: 100, default: 20 } - name: after in: query description: The `next_cursor` of the previous page. schema: { type: string } - name: status in: query schema: { $ref: "#/components/schemas/EmailStatus" } - name: tag in: query description: A tag as `key:value`, e.g. `type:order_confirmation`. schema: { type: string } - name: to in: query description: A recipient address. schema: { type: string, format: email } responses: "200": description: A page of emails. headers: ratelimit-limit: { $ref: "#/components/headers/RateLimitLimit" } ratelimit-remaining: { $ref: "#/components/headers/RateLimitRemaining" } ratelimit-reset: { $ref: "#/components/headers/RateLimitReset" } content: application/json: schema: $ref: "#/components/schemas/EmailList" "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/RestrictedKey" } "429": { $ref: "#/components/responses/TooManyRequests" } "500": { $ref: "#/components/responses/InternalError" } /emails/batch: post: tags: [Emails] operationId: sendEmailBatch summary: Send a batch description: | Up to 100 emails in one request, without attachments. Validation is all-or-nothing: one invalid email and nothing is sent, with every problem listed by index. Charged once for the whole batch. parameters: - $ref: "#/components/parameters/IdempotencyKey" requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/BatchRequest" responses: "200": description: Every email accepted. Ids are in request order. headers: ratelimit-limit: { $ref: "#/components/headers/RateLimitLimit" } ratelimit-remaining: { $ref: "#/components/headers/RateLimitRemaining" } ratelimit-reset: { $ref: "#/components/headers/RateLimitReset" } x-charchy-emails-remaining: { $ref: "#/components/headers/EmailsRemaining" } content: application/json: schema: $ref: "#/components/schemas/BatchResponse" "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "402": { $ref: "#/components/responses/InsufficientBalance" } "403": { $ref: "#/components/responses/SendForbidden" } "409": { $ref: "#/components/responses/IdempotencyConflict" } "413": { $ref: "#/components/responses/PayloadTooLarge" } "422": description: At least one email is invalid. Nothing was sent. content: application/json: schema: $ref: "#/components/schemas/BatchValidationError" "429": { $ref: "#/components/responses/TooManyRequests" } "500": { $ref: "#/components/responses/InternalError" } "503": { $ref: "#/components/responses/SendingUnavailable" } /emails/{id}: parameters: - $ref: "#/components/parameters/EmailId" get: tags: [Emails] operationId: getEmail summary: Get an email description: | An email's status, recipients, tags, timestamps and event timeline. Kept for 30 days. Needs a key with full permission. responses: "200": description: The email. content: application/json: schema: $ref: "#/components/schemas/Email" "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/RestrictedKey" } "404": { $ref: "#/components/responses/NotFound" } "429": { $ref: "#/components/responses/TooManyRequests" } "500": { $ref: "#/components/responses/InternalError" } patch: tags: [Emails] operationId: rescheduleEmail summary: Reschedule an email description: Changes `scheduled_at` while the email is still `scheduled`. requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/RescheduleRequest" responses: "200": description: Rescheduled. content: application/json: schema: $ref: "#/components/schemas/RescheduledEmail" "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/RestrictedKey" } "404": { $ref: "#/components/responses/NotFound" } "422": { $ref: "#/components/responses/Unprocessable" } "429": { $ref: "#/components/responses/TooManyRequests" } "500": { $ref: "#/components/responses/InternalError" } /emails/{id}/cancel: parameters: - $ref: "#/components/parameters/EmailId" post: tags: [Emails] operationId: cancelEmail summary: Cancel an email description: | Cancels an email that is `scheduled` or `queued`. It is refunded and fires `email.canceled`. responses: "200": description: Canceled. content: application/json: schema: $ref: "#/components/schemas/AcceptedEmail" example: id: em_5k2m8x1q9w3r3n5p6r0s2t4v status: canceled "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/RestrictedKey" } "404": { $ref: "#/components/responses/NotFound" } "429": { $ref: "#/components/responses/TooManyRequests" } "500": { $ref: "#/components/responses/InternalError" } /usage: get: tags: [Usage] operationId: getUsage summary: Get usage description: | Where your workspace stands: this term's plan emails, your credits and their expiry, today's cap, the rate limit, and today's test sends. Needs a key with full permission. responses: "200": description: Your usage right now. content: application/json: schema: $ref: "#/components/schemas/Usage" "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/RestrictedKey" } "429": { $ref: "#/components/responses/TooManyRequests" } "500": { $ref: "#/components/responses/InternalError" } /images: post: tags: [Images] operationId: uploadImage summary: Upload an image description: | Hosts an image on files.charchy.krd and returns its permanent public URL, for `` in your emails. PNG, JPEG, GIF or WebP (no SVG), up to 2 MB, up to 200 per workspace. requestBody: required: true content: multipart/form-data: schema: type: object required: [file] properties: file: type: string format: binary description: The image file. responses: "200": description: Uploaded. content: application/json: schema: $ref: "#/components/schemas/Image" "400": { $ref: "#/components/responses/BadRequest" } "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/RestrictedKey" } "413": { $ref: "#/components/responses/PayloadTooLarge" } "429": { $ref: "#/components/responses/TooManyRequests" } "500": { $ref: "#/components/responses/InternalError" } webhooks: email-event: post: operationId: emailEvent summary: Email events description: | Sent to your endpoint when an email changes state. `type` is one of `email.sent`, `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained`, `email.failed`, `email.suppressed`, `email.expired`, `email.canceled`. One event per recipient for `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained` and `email.suppressed` — `data.recipient` names the address. `email.sent`, `email.failed`, `email.expired` and `email.canceled` come once per email. Emails sent with a test key, and the magic addresses, fire these events too. Signed with the Standard Webhooks spec: verify `webhook-signature` against the raw body, reject timestamps older than 5 minutes, and dedupe by `webhook-id`. Order is not guaranteed. Answer 2xx within 5 seconds; `410 Gone` disables the endpoint. Requests carry `user-agent: Charchy-Webhooks/1.0 (+https://charchy.krd/docs/webhooks)`. parameters: - $ref: "#/components/parameters/WebhookId" - $ref: "#/components/parameters/WebhookTimestamp" - $ref: "#/components/parameters/WebhookSignature" requestBody: content: application/json: schema: $ref: "#/components/schemas/EmailWebhookEvent" responses: "2XX": description: Received. Do the work after answering. domain-event: post: operationId: domainEvent summary: Domain events description: | `domain.verified` when a sending domain is verified and ready to send from (again, too, once a domain that lost its records has them back); `domain.failed` when its verification fails — the DKIM records weren't found within 72 hours, or setting the domain up failed — or when a verified domain's records are gone at two daily re-checks a few hours apart. Signed like every event. parameters: - $ref: "#/components/parameters/WebhookId" - $ref: "#/components/parameters/WebhookTimestamp" - $ref: "#/components/parameters/WebhookSignature" requestBody: content: application/json: schema: $ref: "#/components/schemas/DomainWebhookEvent" responses: "2XX": description: Received. account-event: post: operationId: accountEvent summary: Account events description: | `account.paused` when sending is paused for your workspace (whoever paused it), `account.resumed` when it resumes, and `balance.low` when what you have left falls to 20% of what you had after your last top-up (`used_percent: 80`) and when it reaches zero (`100`) — once each per top-up. A top-up is a plan term starting, or credits added. Signed like every event. parameters: - $ref: "#/components/parameters/WebhookId" - $ref: "#/components/parameters/WebhookTimestamp" - $ref: "#/components/parameters/WebhookSignature" requestBody: content: application/json: schema: $ref: "#/components/schemas/AccountWebhookEvent" responses: "2XX": description: Received. components: securitySchemes: apiKey: type: http scheme: bearer description: | `Authorization: Bearer chy_live_…` (or `chy_test_…`). A live key may be sending-only, and may be locked to one domain. parameters: IdempotencyKey: name: Idempotency-Key in: header required: false description: | 1–256 characters, no control characters, kept 24 hours per workspace. The same key with the same body returns the first response again; with a different body, `409 idempotency_conflict`; an empty, too long or malformed key, `400 invalid_idempotency_key`. Send one on every request, e.g. `/`. schema: { type: string, minLength: 1, maxLength: 256 } example: order-confirmation/4821 EmailId: name: id in: path required: true schema: { type: string, pattern: "^em_" } example: em_8f2k1x9q4w7m3n5p6r0s2t4v WebhookId: name: webhook-id in: header required: true description: The event's id (`evt_…`), the same on every retry. Dedupe by it. schema: { type: string } WebhookTimestamp: name: webhook-timestamp in: header required: true description: Unix seconds when this attempt was signed. Reject if older than 5 minutes. schema: { type: string } WebhookSignature: name: webhook-signature in: header required: true description: | One or more `v1,`, separated by spaces (two during a secret rotation). schema: { type: string } headers: RateLimitLimit: description: Requests allowed in the current window. schema: { type: integer } RateLimitRemaining: description: Requests left in the current window. schema: { type: integer } RateLimitReset: description: Seconds until the window resets. schema: { type: integer } EmailsRemaining: description: Emails left to spend — this month's plan emails plus credits. schema: { type: integer } RetryAfter: description: Seconds to wait before retrying. schema: { type: integer } schemas: EmailStatus: type: string enum: - scheduled - queued - sending - sent - delivered - delivery_delayed - bounced - complained - canceled - expired - suppressed - failed - unknown description: | `sent` = our delivery infrastructure accepted it; `delivered` = the receiving server did. `unknown` = no delivery event 30 minutes after an uncertain send (never re-sent; the charge stays). With several recipients the status sums them up: `complained` if any recipient complained, else `bounced` if any bounced, else `delivered` once EVERY recipient was delivered, else `delivery_delayed` if any is delayed, else `sent`. Each recipient's own events are in `events`, with `recipient`. Address: type: string description: "`address@domain` or `Name `. Display names may be Kurdish or Arabic." examples: ["Darin Game "] AddressList: description: One address, or an array of them. oneOf: - $ref: "#/components/schemas/Address" - type: array items: { $ref: "#/components/schemas/Address" } Tags: type: object maxProperties: 10 description: Up to 10 pairs; keys and values use letters, digits, `_` and `-`, up to 256 characters. propertyNames: { pattern: "^[A-Za-z0-9_-]{1,256}$" } additionalProperties: { type: string, pattern: "^[A-Za-z0-9_-]{1,256}$" } examples: [{ type: order_confirmation }] TagsInput: description: | Tags as an object (`{ "type": "order" }`) or as an array of name/value pairs (`[{ "name": "type", "value": "order" }]`). Either way they come back as an object. oneOf: - $ref: "#/components/schemas/Tags" - type: array maxItems: 10 items: type: object required: [name, value] properties: name: { type: string, pattern: "^[A-Za-z0-9_-]{1,256}$" } value: { type: string, pattern: "^[A-Za-z0-9_-]{1,256}$" } Attachment: type: object required: [filename, content, content_type] properties: filename: { type: string, examples: [invoice-4821.pdf] } content: { type: string, contentEncoding: base64, description: "The file, base64-encoded." } content_type: { type: string, examples: [application/pdf] } content_id: type: string description: Makes this an inline image, shown by `` in the html. EmailFields: type: object required: [from, to, subject] properties: from: $ref: "#/components/schemas/Address" to: $ref: "#/components/schemas/AddressList" description: "`to` + `cc` + `bcc` together: at most 50 addresses." cc: $ref: "#/components/schemas/AddressList" bcc: $ref: "#/components/schemas/AddressList" reply_to: $ref: "#/components/schemas/AddressList" subject: { type: string, maxLength: 998 } html: { type: string, description: "Up to 512 KB. Give `html`, `text` or both." } text: { type: string, description: "Up to 512 KB. Generated from `html` when missing." } headers: type: object maxProperties: 20 additionalProperties: { type: string } description: | Custom headers. Reserved, refused: From, To, Cc, Bcc, Subject, Reply-To, DKIM-*, Return-Path, Message-ID, X-SES-*. No CR or LF in names or values. `List-Unsubscribe` and `List-Unsubscribe-Post` (RFC 8058 one-click) are allowed. tags: $ref: "#/components/schemas/TagsInput" scheduled_at: type: string format: date-time description: Up to 30 days ahead. In the past = now. expires_at: type: string format: date-time description: If the email can't leave by then, it is dropped as `expired` and refunded. SendEmailRequest: allOf: - $ref: "#/components/schemas/EmailFields" - type: object properties: attachments: type: array maxItems: 3 description: Up to 3 files, 3 MB together before base64. items: { $ref: "#/components/schemas/Attachment" } AcceptedEmail: type: object required: [id, status] properties: id: { type: string, examples: [em_8f2k1x9q4w7m3n5p6r0s2t4v] } status: { $ref: "#/components/schemas/EmailStatus" } BatchRequest: type: object required: [emails] properties: emails: type: array minItems: 1 maxItems: 100 description: Same fields as a single email, without attachments. items: { $ref: "#/components/schemas/EmailFields" } BatchResponse: type: object required: [emails] properties: emails: type: array items: { $ref: "#/components/schemas/AcceptedEmail" } RescheduleRequest: type: object required: [scheduled_at] properties: scheduled_at: { type: string, format: date-time } RescheduledEmail: type: object required: [id, status, scheduled_at] properties: id: { type: string } status: { type: string, const: scheduled } scheduled_at: { type: string, format: date-time } EmailEvent: type: object required: [type, at] properties: type: { $ref: "#/components/schemas/EmailStatus" } at: { type: string, format: date-time } recipient: { type: string, format: email, description: Set on per-recipient events (delivered, delayed, bounced, complained, suppressed). } bounce: $ref: "#/components/schemas/BounceDetails" reason: $ref: "#/components/schemas/EndReason" message: { type: string, description: "Why, in words (`failed`)." } simulated: { type: boolean, description: Played out by test mode or a magic address — nothing was sent. } EndReason: type: string description: Why an email ended without being delivered (`failed`, `expired`, `unknown` events). enum: - expires_at - held_too_long - domain_not_verified - rejected - retries_exhausted - content_missing - recipient_not_allowed - no_answer BounceDetails: type: object properties: type: { type: string, enum: [permanent, transient, undetermined], description: "`permanent` = a hard bounce; the address is suppressed." } sub_type: { type: string, examples: [general, no_email, suppressed, mailbox_full, message_too_large] } message: { type: string, examples: ["The recipient's mail server refused the email: the address does not exist."] } diagnostic_code: { type: string, examples: ["smtp; 550 5.1.1 user unknown"] } EmailSummary: type: object required: [id, status, from, to, subject, tags, test, created_at, scheduled_at] properties: id: { type: string } status: { $ref: "#/components/schemas/EmailStatus" } from: { type: string } to: { type: array, items: { type: string } } subject: { type: string } tags: { $ref: "#/components/schemas/Tags" } test: { type: boolean, description: Sent with a test key. } created_at: { type: string, format: date-time } scheduled_at: { type: [string, "null"], format: date-time } Email: type: object required: [id, status, from, to, cc, bcc, reply_to, subject, tags, test, created_at, scheduled_at, expires_at, events] properties: id: { type: string } status: { $ref: "#/components/schemas/EmailStatus" } from: { type: string } to: { type: array, items: { type: string } } cc: { type: array, items: { type: string } } bcc: { type: array, items: { type: string } } reply_to: { type: array, items: { type: string } } subject: { type: string } tags: { $ref: "#/components/schemas/Tags" } test: { type: boolean, description: Sent with a test key. } created_at: { type: string, format: date-time } scheduled_at: { type: [string, "null"], format: date-time } expires_at: { type: [string, "null"], format: date-time } events: type: array items: { $ref: "#/components/schemas/EmailEvent" } EmailList: type: object required: [data, has_more] properties: data: type: array items: { $ref: "#/components/schemas/EmailSummary" } has_more: { type: boolean } next_cursor: { type: string, description: "Pass as `after` for the next page." } Usage: type: object required: [plan, credits, daily, rate_limit, test] properties: plan: description: The current monthly plan, or null without one. oneOf: - type: "null" - type: object required: [key, emails_included, emails_used, emails_left, term_ends_at] properties: key: { type: string, enum: [starter, growth, pro, scale], description: The plan. } emails_included: { type: integer } emails_used: { type: integer } emails_left: { type: integer } term_ends_at: { type: string, format: date-time } credits: description: Pay-as-you-go credits, or null with none. oneOf: - type: "null" - type: object required: [emails, expires_at] properties: emails: { type: integer } expires_at: { type: string, format: date-time, description: One expiry for the whole balance. } daily: type: object required: [cap, surge_cap, used, resets_at] properties: cap: { type: integer, description: Recipients a rolling 24 hours your plan (or credits) gives. } surge_cap: type: integer description: | The most a rush may reach while your recent sending is healthy: up to twice a plan's or the credits-only cap, never during the sandbox or the first week. Equal to `cap` when there is no surge. Requests are refused with `daily_limit_reached` past this, not past `cap`. used: { type: integer } resets_at: { type: string, format: date-time, description: "When there is room again at `surge_cap`, or when `used` next goes down." } rate_limit: type: object required: [requests_per_second, burst] properties: requests_per_second: { type: integer, examples: [10] } burst: { type: integer, examples: [20] } test: type: object required: [daily_cap, used] properties: daily_cap: { type: integer, examples: [1000] } used: { type: integer } examples: - plan: { key: growth, emails_included: 50000, emails_used: 12840, emails_left: 37160, term_ends_at: "2026-12-14T09:00:00Z" } credits: { emails: 25000, expires_at: "2027-02-10T00:00:00Z" } daily: { cap: 5000, surge_cap: 10000, used: 612, resets_at: "2026-11-17T00:00:00Z" } rate_limit: { requests_per_second: 10, burst: 20 } test: { daily_cap: 1000, used: 37 } Image: type: object required: [id, url, content_type, size] properties: id: { type: string, examples: [img_4t8w2k6m1q3n5p6r0s2t4v9x] } url: { type: string, format: uri, examples: ["https://files.charchy.krd/i/4t8w2k6m1q3n5p6r0s2t4v9x/logo.png"] } content_type: { type: string, enum: [image/png, image/jpeg, image/gif, image/webp] } size: { type: integer, description: Bytes. } ErrorCode: type: string enum: - invalid_json - invalid_idempotency_key - validation_error - missing_api_key - invalid_api_key - restricted_api_key - domain_not_verified - sender_not_allowed - not_approved - sending_paused - not_found - idempotency_conflict - idempotency_in_flight - payload_too_large - invalid_attachment - too_many_recipients - schedule_out_of_range - insufficient_balance - rate_limit_exceeded - daily_limit_reached - internal_error - sending_unavailable Error: type: object required: [error] properties: error: type: object required: [code, message] properties: code: { $ref: "#/components/schemas/ErrorCode" } message: { type: string, description: "For people; may change. Match on `code`." } field: { type: string, description: "The request field at fault, when there is one." } docs: { type: string, format: uri, examples: ["https://charchy.krd/docs/errors#domain_not_verified"] } BatchValidationError: type: object required: [error] properties: error: type: object required: [code, message, items] properties: code: { type: string, const: validation_error } message: { type: string } docs: { type: string, format: uri } items: type: array items: type: object required: [index, code, message] properties: index: { type: integer, description: "The email's position in `emails`, from 0." } code: { $ref: "#/components/schemas/ErrorCode" } field: { type: string } message: { type: string } WebhookEventBase: type: object required: [id, type, created_at, data] properties: id: { type: string, description: "Same as the `webhook-id` header.", examples: [evt_2b7k9x4m1q8w3n5p6r0s2t4v] } created_at: { type: string, format: date-time, description: When it happened. Order events by it. } test: { type: boolean, description: "Present and true on a sample from Send test event (no real email behind it). Whether a real email used a test key is `data.test`." } EmailWebhookEvent: allOf: - $ref: "#/components/schemas/WebhookEventBase" - type: object required: [type, data] properties: type: type: string enum: - email.sent - email.delivered - email.delivery_delayed - email.bounced - email.complained - email.failed - email.suppressed - email.expired - email.canceled data: type: object required: [email_id, from, to, subject, created_at, tags, test] properties: email_id: { type: string } from: { type: string } to: { type: array, items: { type: string } } subject: { type: string } created_at: { type: string, format: date-time, description: When the email was accepted. } tags: { $ref: "#/components/schemas/Tags" } test: type: boolean description: | Sent with a test key — the same as `test` on `GET /v1/emails/{id}`. Not the top-level `test`, which marks a sample from Send test event. recipient: type: string description: | The address this event is about — on `email.delivered`, `email.delivery_delayed`, `email.bounced`, `email.complained` and `email.suppressed`, which come once per recipient. May be a `cc` or `bcc` address. examples: [customer@example.com] bounce: $ref: "#/components/schemas/BounceDetails" description: "`email.bounced` only." suppressed: type: object description: "`email.suppressed` only." properties: reason: { type: string, enum: [previous_bounce, previous_complaint] } failed: type: object description: "`email.failed` only. Refunded." properties: reason: { type: string, description: "Why, in words.", examples: ["daringaming.com is no longer verified."] } expired: type: object description: "`email.expired` only. Refunded." properties: reason: type: string description: Why, in words — its `expires_at` passed, or it waited 3 days while sending was paused. examples: ["It could not leave before its expires_at, so it was dropped."] examples: - id: evt_2b7k9x4m1q8w3n5p6r0s2t4v type: email.delivered created_at: "2026-11-16T09:00:02.400Z" data: email_id: em_8f2k1x9q4w7m3n5p6r0s2t4v from: Darin Game to: [customer@example.com] subject: "Your order #4821" created_at: "2026-11-16T09:00:00.120Z" tags: { type: order_confirmation } test: false recipient: customer@example.com DomainWebhookEvent: allOf: - $ref: "#/components/schemas/WebhookEventBase" - type: object required: [type, data] properties: type: { type: string, enum: [domain.verified, domain.failed] } data: type: object required: [domain] properties: domain: { type: string, examples: [daringaming.com] } AccountWebhookEvent: allOf: - $ref: "#/components/schemas/WebhookEventBase" - type: object required: [type, data] properties: type: { type: string, enum: [account.paused, account.resumed, balance.low] } data: type: object description: "`account.paused`: `code` and `reason`. `account.resumed`: empty. `balance.low`: `used_percent` and `emails_left`." properties: code: type: string enum: [manual, bounce_rate, complaint_rate, volume_spike, not_transactional, provider_paused, reputation_finding] description: "Why sending was paused (`account.paused`): our team, too many hard bounces, spam complaints, mail that looks like marketing, or our delivery provider's own reputation checks (`provider_paused`, `reputation_finding`). `volume_spike` no longer pauses sending; only events from before 2026-11-17 carry it." reason: { type: string, description: "The same, in words, with our numbers when we have them (`account.paused`)." } used_percent: { type: integer, enum: [80, 100], description: "`balance.low`: 80 when 20% or less is left since your last top-up, 100 when nothing is left." } emails_left: { type: integer, description: "`balance.low`: plan emails plus usable credits left." } responses: BadRequest: description: "`invalid_json`, `validation_error` (with `field`) or `invalid_idempotency_key`." content: application/json: schema: { $ref: "#/components/schemas/Error" } example: error: code: validation_error field: to message: '"ara@" is not an email address.' docs: https://charchy.krd/docs/errors#validation_error Unauthorized: description: "`missing_api_key` or `invalid_api_key` (unknown or revoked)." content: application/json: schema: { $ref: "#/components/schemas/Error" } example: error: code: invalid_api_key message: This API key is unknown or was revoked. docs: https://charchy.krd/docs/errors#invalid_api_key InsufficientBalance: description: "`insufficient_balance` — plan emails and credits are both used up. Don't retry automatically." content: application/json: schema: { $ref: "#/components/schemas/Error" } example: error: code: insufficient_balance message: This month's plan emails and your credits are used up. docs: https://charchy.krd/docs/errors#insufficient_balance SendForbidden: description: | `restricted_api_key`, `domain_not_verified`, `sender_not_allowed`, `not_approved` or `sending_paused`. content: application/json: schema: { $ref: "#/components/schemas/Error" } example: error: code: domain_not_verified message: daringaming.com is not verified in this workspace. docs: https://charchy.krd/docs/errors#domain_not_verified RestrictedKey: description: "`restricted_api_key` — a sending-only key on a read endpoint." content: application/json: schema: { $ref: "#/components/schemas/Error" } example: error: code: restricted_api_key message: This key can only send emails. docs: https://charchy.krd/docs/errors#restricted_api_key NotFound: description: "`not_found`." content: application/json: schema: { $ref: "#/components/schemas/Error" } example: error: code: not_found message: No email with this id in your workspace. docs: https://charchy.krd/docs/errors#not_found IdempotencyConflict: description: "`idempotency_conflict` (same key, different body) or `idempotency_in_flight` (retry shortly)." content: application/json: schema: { $ref: "#/components/schemas/Error" } example: error: code: idempotency_conflict message: This Idempotency-Key was used with a different body. docs: https://charchy.krd/docs/errors#idempotency_conflict PayloadTooLarge: description: "`payload_too_large` — body over 5 MB, or `html`/`text` over 512 KB." content: application/json: schema: { $ref: "#/components/schemas/Error" } example: error: code: payload_too_large message: The request body is over 5 MB. docs: https://charchy.krd/docs/errors#payload_too_large Unprocessable: description: "`invalid_attachment`, `too_many_recipients` or `schedule_out_of_range`." content: application/json: schema: { $ref: "#/components/schemas/Error" } example: error: code: schedule_out_of_range field: scheduled_at message: scheduled_at is more than 30 days ahead. docs: https://charchy.krd/docs/errors#schedule_out_of_range TooManyRequests: description: "`rate_limit_exceeded` (over 10 requests a second) or `daily_limit_reached`. Retry after `Retry-After`." headers: Retry-After: { $ref: "#/components/headers/RetryAfter" } ratelimit-limit: { $ref: "#/components/headers/RateLimitLimit" } ratelimit-remaining: { $ref: "#/components/headers/RateLimitRemaining" } ratelimit-reset: { $ref: "#/components/headers/RateLimitReset" } content: application/json: schema: { $ref: "#/components/schemas/Error" } example: error: code: rate_limit_exceeded message: More than 10 requests a second. docs: https://charchy.krd/docs/errors#rate_limit_exceeded InternalError: description: "`internal_error`. Retry with backoff and the same Idempotency-Key." content: application/json: schema: { $ref: "#/components/schemas/Error" } SendingUnavailable: description: "`sending_unavailable` — sending is halted platform-wide for a while. Retry with backoff." content: application/json: schema: { $ref: "#/components/schemas/Error" } ```