# Set up Sendtern in a repository Use this guide from your coding agent or terminal. Select Codex, Claude Code, or OpenCode on the documentation page to copy a prompt for the same workflow. ## 1. Identify the integration Find the server-side code that sends mail, its configuration schema, and the existing tests. Use the repository's runtime and conventions. Ask only for requirements still missing, such as the email event or production sender. Keep existing email templates and unrelated features intact. ## 2. Configure access - Create a project and a sending-only key in the dashboard. Put the key in the application's secret manager as `SENDTERN_API_KEY`. - Add placeholders to the checked-in configuration example. Keep actual keys out of chat, source files, client bundles, and request logs. - Use an owner session or a separate full-access key for resource administration. The application's key only needs sending permissions. ## 3. Implement and test with Email Playground Write or update a server-side function. Keep a stable `Idempotency-Key` for each business event so transient HTTP failures can be retried without creating a new message. Check the SDK or HTTP result before treating the email as queued. ```bash curl --fail-with-body https://sendtern.com/test/emails \ -H "Authorization: Bearer $SENDTERN_API_KEY" \ -H 'Content-Type: application/json' \ -H 'Idempotency-Key: integration-check-001' \ -d '{"from":"sandbox@sendtern.test","to":"recipient@example.com","subject":"Integration test","text":"Captured by Sendtern."}' ``` A successful capture returns an ID. Inspect the message in Email Playground. A sending key restricted to a verified domain must use that domain in `from`, including when testing. You can also use the Resend Node.js SDK with the test base URL `https://sendtern.com/test` for `emails.send`. Run the existing automated tests. If a key is unavailable, finish the code and mock the integration, then report the step still needed. ## 4. Move to production when approved Add the exact sender domain in Sendtern, publish the DNS records shown in the dashboard, and verify it. If DNS changes require access you do not have, give the operator the records and continue with the test integration. Use the approved sender address and use the production API path `https://sendtern.com/emails` or the Resend Node.js SDK base `https://sendtern.com/resend`. Replace any sample recipient with an approved address before making a real send. ```js import { Resend } from 'resend'; const mail = new Resend(process.env.SENDTERN_API_KEY, { baseUrl: 'https://sendtern.com/resend', }); export async function sendReceipt({ eventId, recipient, text }) { const { data, error } = await mail.emails.send({ from: process.env.SENDTERN_FROM, to: recipient, subject: 'Payment receipt', text, }, { idempotencyKey: 'receipt-' + eventId }); if (error) throw new Error(error.message); return data.id; } ``` When migrating an existing Resend integration, reuse its mail calls wherever the [compatibility contract](https://sendtern.com/agent.md#migrate-from-resend) covers them. Create new Sendtern keys and verify the sender domain in Sendtern. Use the delivery timeline to distinguish app acceptance, SMTP acceptance, delay, and bounce. Report the changes, tests, actual capture ID when available, and remaining configuration. For DNS and spam checks see the [deliverability guide](https://sendtern.com/deliverability.md). For machine-readable endpoints use [OpenAPI](https://sendtern.com/openapi.json). --- # Sendtern API for humans and AI agents Sendtern queues transactional emails, checks sending domains, manages API credentials, and records delivery progress. ## Set up an integration 1. Use the base URL supplied by the workspace operator. Local development defaults to `http://localhost:3000`. The production example is `https://sendtern.com`. 2. Create a **sending-only** key in the dashboard and load it from `SENDTERN_API_KEY` in your server environment. Keep it out of browser code, logs, and repository files. For domain administration or email status, use a separate full-access key. 3. In sandbox mode use `sandbox@sendtern.test` or a verified domain. A sandbox request appears in the email log and never contacts the recipient. In live SMTP mode use the exact verified sender domain. 4. Call `POST /emails` with JSON and a stable `Idempotency-Key` when you may retry the same operation. Store the returned ID. 5. When you need delivery status, use `GET /emails/{id}` with a full-access key. Report acceptance and delivery using the explicit state from that endpoint. ```bash curl http://localhost:3000/emails \ -H "Authorization: Bearer $SENDTERN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: welcome-example-001" \ -d '{ "from": "sandbox@sendtern.test", "to": ["demo@example.com"], "subject": "Welcome", "text": "Your Sendtern integration is working." }' ``` An accepted request returns HTTP 200 and `{"id":""}`. The response arrives after the queue has been saved. ## Authentication and errors Every public resource endpoint below requires `Authorization: Bearer st_…`. `sending_access` allows transactional submission and batch submission. `full_access` allows management of resources in the same workspace. Keys are returned once on creation, and revocation takes effect on subsequent requests. Errors have the shape `{"name":"validation_error","message":"…","statusCode":422}`. Common statuses include `400` for malformed JSON, `401` for missing or invalid credentials, `403` for permissions or sender-domain errors, `404` for unknown resources, `409` for conflicts, `413` for a body over 1 MB, `415` for unsupported media, `422` for validation, `429` for rate or recipient quotas, and `503` for a temporary DNS lookup failure. Honor `Retry-After` when present. Retry transient HTTP failures with backoff and the same idempotency key. ## Emails | Method | Path | Result | | --- | --- | --- | | POST | `/emails` | Queue an email and return its ID | | POST | `/emails/batch` | Queue up to 100 emails and return `{data:[{id},…]}` | | GET | `/emails` | Return `{object:"list",data:[…],has_more:boolean}` | | GET | `/emails/{id}` | Return metadata, the stored message, and its event timeline | `POST /emails` accepts `from`, `to`, `subject`, plus `text`, `html`, or both. Optional fields are `cc`, `bcc`, `reply_to`, and `tags`. The sender may use the format `Name `. Recipient fields accept a string or an array of strings, with a maximum of 50 recipients across To, Cc and Bcc. A message accepts up to ten tags with names and values made up of letters, digits, underscores, or hyphens. Tags are stored with the message for application use. To send from a published template, pass its ID or alias and any variables the template uses. ```json { "to": "customer@example.com", "template": { "id": "welcome", "variables": { "first_name": "Ada" } } } ``` The published snapshot supplies the HTML, sender, subject, and optional reply address. Use `{{first_name}}` syntax in the editor. Variable values are escaped in HTML. Missing variables return HTTP 422. Publish again to update the snapshot used for sending. For 24 hours, an idempotency key returns the original ID for the same normalized payload. Reusing it for a different payload returns HTTP 409. The `mode` field is `sandbox` or `live`. Transactional quotas count recipients and reset at the applicable UTC day or month boundary. The selected plan determines the daily and monthly limits. List filters include `limit` (1–100, default 30), `after` (last email ID from the previous page), `q` (subject or To address), and `status`. A detail response adds `text`, `html`, `error` and `events` to the metadata. Each event has a `kind`, `created_at` and optional `detail`. ### Delivery states | State | Meaning | | --- | --- | | `queued`, `sending` | Saved locally or being submitted to the local MTA | | `captured` | Stored in sandbox with no outbound network delivery | | `skipped` | Removed from the campaign queue before SMTP submission, for example after an unsubscribe | | `sent` | The local MTA accepted the submission | | `delayed` | At least one destination returned a temporary failure and the MTA is retrying | | `delivered` | Every destination accepted the message over SMTP | | `bounced` | At least one recipient ended in failure. Inspect the timeline for each recipient | | `failed` | Local submission failed | | `uncertain` | SMTP handoff could not be confirmed. Check the timeline before retrying with a different key | Destination acceptance does not establish inbox placement. The default outbound setup reports SMTP delivery and rejection events, including queue expiration. Later asynchronous bounce mail and complaint feedback require an inbound mail path that is outside this release. An unknown-recipient SMTP response (`5.1.1`) adds that address to the workspace suppression list. ## Domains and keys | Method | Path | Body or result | | --- | --- | --- | | POST | `/domains` | `{"name":"mail.example.com"}`; returns the domain and DNS records | | GET | `/domains` | List domains and their records | | GET | `/domains/{id}` | Read one domain | | POST | `/domains/{id}/verify` | Check TXT ownership and, for live mode, DKIM and the suggested SPF mechanism | | DELETE | `/domains/{id}` | Remove a domain from the workspace | | POST | `/api-keys` | `{"name":"Backend","permission":"sending_access"}`; returns `id` and `token` | | GET | `/api-keys` | List metadata and token prefixes | | DELETE | `/api-keys/{id}` | Revoke a key and return HTTP 204 | Domain records expose `type`, fully qualified `name`, `value`, and `status`. An existing SPF policy should be extended with the published sending IPv4 mechanism. The domain ownership TXT and DKIM TXT records must match before live mail can be queued. A domain registered previously in sandbox needs to be re-added in live mode so it receives a DKIM key. A sending-only key can include the optional `domain` field. Use the exact verified domain name in the workspace. ## Migrate from Resend Set the Node.js SDK base URL to the Sendtern `/resend` endpoint and use a Sendtern API key. Verify your sender domain in Sendtern using its new DNS records. Existing Resend resource IDs and API keys belong to the original provider. ```js import { Resend } from 'resend'; const resend = new Resend(process.env.SENDTERN_API_KEY, { baseUrl: 'https://sendtern.com/resend', }); const { data, error } = await resend.emails.send({ from: 'Reports ', to: 'recipient@example.com', subject: 'Your report is ready', text: 'Sign in to see your report.', replyTo: 'support@your-verified-domain.example', }, { idempotencyKey: 'report-123' }); if (error) throw new Error(error.message); ``` SDK clients that support a configurable endpoint can also set `RESEND_BASE_URL` to the same URL. The Node SDK renders JSX client-side. Raw API callers must send `html` or `text` directly, or specify a published Sendtern template. | SDK calls | Scope | | --- | --- | | `emails.send`, `emails.get`, `emails.list` | Standard transactional fields, safe custom headers, and inline base64 attachments up to 500 KiB total. List endpoints accept forward `after` and backward `before` cursors. | | `emails.update`, `emails.cancel` | Future scheduled emails. The timestamp accepts an ISO value with timezone or `in N seconds/minutes/hours/days`, up to 30 days ahead. Accepted SMTP submissions cannot be canceled. | | `batch.send` | Up to 100 messages. Strict validation is all-or-nothing. Permissive mode may reject individual invalid rows with their original indexes. Batch accepts immediate messages without attachments. | | `domains.create`, `domains.get`, `domains.list`, `domains.verify`, `domains.remove` | Sendtern ownership and DKIM records using relative names; results reflect the local MTA. Domain switching across cloud regions and provider-specific tracking options are unavailable. | | `apiKeys.create`, `apiKeys.list`, `apiKeys.remove` | Supports domain-scoped `sending_access` using a verified `domain_id`. Compatible key creation defaults to `full_access`; explicitly select `sending_access` for a sending integration. | The compatibility endpoint never downloads attachment URLs or reads local attachment paths. Keep existing Sendtern URLs for the workspace's native webhook signature, delivery event timeline, and provider-specific queue states. `queued` in compatibility responses only indicates acceptance for processing. List or retrieval access requires full access. On `/resend` the standard error object includes `name`, `message`, and `statusCode`. Names include `missing_api_key`, `restricted_api_key`, `validation_error`, `invalid_idempotent_request`, and `daily_quota_exceeded`. For send and batch retries, keep the original request body and the same idempotency key for up to 24 hours. Treat local queue acceptance and successful SMTP acceptance as separate states. ## Test inbox Post to `/test/emails` to capture a message for inspection. It is saved in the project's [Email Playground](/dashboard/playground) without using SMTP or live send quota. The dashboard displays HTML, plain text, MIME headers, links, and attachments, and offers a download of the original `.eml`. External resources are blocked during preview. The most recent 50 captures remain available for up to seven days. ```bash curl https://sendtern.com/test/emails \ -H "Authorization: Bearer $SENDTERN_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: receipt-test-123" \ -d '{"from":"dev@example.com","to":"preview@example.com","subject":"Receipt test","text":"Test receipt"}' ``` The response contains the captured email ID. Use `https://sendtern.com/test` as the base URL for the Resend SDK's `emails.send` call. The endpoint accepts inline base64 attachments and basic email fields. Both the endpoint and dashboard are isolated by project. A domain-scoped API key still requires its assigned sender domain. Development messages sent through the regular API are capture-only, and appear in the project's Emails view. ## Webhook delivery Register a public HTTPS endpoint in the dashboard and store the signing secret when it is displayed. Sendtern posts JSON with an event `id`, `type`, `created_at`, and `data`. The `X-Sendtern-Timestamp` header is a Unix timestamp in seconds. Verify the `X-Sendtern-Signature` header by computing HMAC-SHA256 over the literal timestamp, a dot, and the raw request body. Use the entire `whsec_` value as the key. The header is `v1=` followed by the hex digest. Compare the digest in constant time and reject stale timestamps. Deduplicate events by their JSON `id`. A `2xx` response acknowledges delivery. Sendtern retries other responses or network failures up to five total attempts. The `X-Sendtern-Delivery` header identifies the delivery across retries. An SMTP outcome can generate one event per recipient. Its `data` includes the recipient, the SMTP status code, and the email ID. Fetch `GET /emails/{id}` for the aggregate message state. Subscribe to `domain.health_changed` to receive DNS warnings and recoveries for verified domains. Data includes `domain_id`, `name`, `state`, and the affected DNS checks in `issues`. A temporary resolver outage does not generate a DNS-change alert. See the domain's Email Health Monitor for the latest findings and suggested fixes. ## Automation events Register an event and configure the workflow in the dashboard. Call `POST /events` with a full-access key and JSON such as `{"event":"user.created","email":"recipient@example.com","data":{"first_name":"Ada"}}`. The API returns `202` with the run IDs and the number of waiting runs resumed. Set `Idempotency-Key` to protect retries for 24 hours. The workflow snapshots its steps when it starts. Pausing it stops new enrollments. Existing runs continue. A test run captures emails in the sandbox and leaves contacts unchanged. Conditions for clicks and opens read event data submitted by your application. ## More resources - [Human documentation](/docs) - [OpenAPI schema](/openapi.json) - [Documentation index](/llms.txt) --- # Diagnose delivery and inbox placement `delivered` means the recipient provider accepted the message over SMTP. Check the recipient's inbox, spam folder, and original headers to verify placement and authentication. For Gmail, use **More → Show original**. Record the Sendtern email ID and the recipient's `Authentication-Results` header, with personal data removed where possible. ## Confirm sender authentication - Check that the sending IP's PTR points to the SMTP hostname and that this hostname's A record points back to the same IPv4. The server provider manages the PTR. - Verify the sender domain in Sendtern. Check for one SPF policy with the correct sending IP, the DKIM selector and key shown by Sendtern, and DMARC for the sender domain. - In the received headers, inspect `spf=`, `dkim=`, and `dmarc=`. Compare the From domain against the passing SPF or DKIM domain to confirm alignment. ## If the message lands in Spam Use a consistent, verified sender and email recipients who expect the message. Increase legitimate traffic gradually on a new sending IP or domain. Check bounce and complaint rates and use the dashboard delivery timeline for provider errors. DNS and authentication are inputs to placement alongside recipient-provider reputation and engagement. See [Google's sender guidelines](https://support.google.com/mail/answer/81126). ### Check placement before increasing traffic In production, `mail.sendtern.com` is the outbound SMTP hostname, inbound MX hostname and message ID domain. The website, incoming mail listener and local KumoMTA are hosted on Kamatera. Verify that the A record points to `185.167.99.26` and that Kamatera publishes the matching PTR. A missing or mismatched PTR degrades local SMTP status even when remote MX servers accept connections. The status monitor records Outlook.com network blocks (`S3140` or `S3150`) from actual SMTP responses, even when the provider accepts connections. A later accepted Outlook.com message from the gateway clears the recorded block. 1. Use controlled Gmail, Outlook.com and Yahoo accounts that have not already trained their filters on Sendtern messages. Test the actual confirmation and password-reset flows and an email through the production API. For each message, record the Sendtern ID, sending IP, remote SMTP response, mailbox folder, and authentication results. Keep confirmation and recovery tokens out of the report. 2. Verify the current DMARC record at the authoritative DNS servers and through multiple public resolvers after a change. If one mailbox shows `dmarc=pass` and another omits the result, compare the message times and retry the placement check after the previous DNS response's cache lifetime has elapsed. 3. Check a sending IP in Spamhaus ZEN and compare the result with a control query. Spamhaus response `127.255.255.254` signals a public-resolver restriction. Public blocklist checks and Gmail reputation measurements cover different signals. See the [Spamhaus DNSBL FAQ](https://www.spamhaus.org/faqs/dnsbl-usage/). 4. Verify `sendtern.com` in [Google Postmaster Tools](https://support.google.com/mail/answer/9981691). Data can be unavailable at low volume. For Outlook.com, request IP access in [SNDS](https://substrate.office.com/ip-domain-management-snds/snds) and configure JMRP. Enroll each active DKIM signing domain in the [Yahoo Complaint Feedback Loop](https://senders.yahooinc.com/complaint-feedback-loop/). Keep registration and recovery traffic on a dedicated route before increasing public sending volume. Use consented traffic, and verify complaint and asynchronous bounce ingestion before enabling large campaigns. The current delivery timeline records SMTP responses. Complaint counts are meaningful only after a provider feedback feed is connected and tested. ## If text looks garbled Check the subject and body saved by Sendtern before looking at SMTP. If the stored text is already garbled, verify that the submitting application encodes JSON as UTF-8, especially through terminal pipes and remote scripts. In Email Playground, inspect the parsed text and download the original message to validate MIME before sending a live test. If the stored text is correct, compare its MIME subject, charset, and transfer encoding against the recipient's original message. Use the [service status](https://sendtern.com/status) for provider connection checks and queue availability. --- # Sendtern documentation > Markdown articles from the Sendtern documentation. Start with the API guide for the complete HTTP contract. ## Get started - [Introduction](https://sendtern.com/docs/index.md): Sendtern is the transactional email API for developers. - [Quickstart](https://sendtern.com/docs/quickstart.md): Send your first email in under five minutes. - [Create an API key](https://sendtern.com/docs/authentication.md): Authenticate every request with a scoped bearer token. - [Add a domain](https://sendtern.com/docs/domains.md): Verify your domain with SPF, DKIM and an ownership record. - [Transactional email](https://sendtern.com/docs/email-types.md): Use transactional emails for actions and campaigns for opted-in audiences. - [AI onboarding](https://sendtern.com/docs/agents.md): Let coding assistants and agents work with Sendtern safely. ## Sending examples - [Send with Node.js](https://sendtern.com/docs/send-with-nodejs.md): Send email from any Node.js 18+ project using the built-in fetch. - [Send with Next.js](https://sendtern.com/docs/send-with-nextjs.md): Send from a Route Handler so the key never reaches the browser. - [Send with Python](https://sendtern.com/docs/send-with-python.md): Send email from Python with the requests library. - [Send with cURL](https://sendtern.com/docs/send-with-curl.md): Send straight from the terminal to test your setup. ## Learn - [Sending emails](https://sendtern.com/docs/sending.md): Everything a send request can carry, and what happens after. - [Idempotency keys](https://sendtern.com/docs/idempotency.md): Retry any request safely, without sending the same email twice. - [Statuses & events](https://sendtern.com/docs/statuses.md): What each email status means and when it's final. - [Errors](https://sendtern.com/docs/errors.md): Every error code, what causes it and how to fix it. - [Rate limits & quotas](https://sendtern.com/docs/rate-limits.md): How much you can send and how to stay within limits. - [Deliverability](https://sendtern.com/docs/deliverability.md): Practical steps to land in the inbox. - [Telegram notifications](https://sendtern.com/docs/notifications.md): Get delivery problems in a Telegram chat as they happen. - [Key security](https://sendtern.com/docs/security.md): Keep API keys secret and recover quickly if one leaks. - [Track delivery events](https://sendtern.com/docs/delivery.md): What each email status means and when it's final. ## Resources - [llms.txt](https://sendtern.com/docs/llms.md): These docs in plain text, for LLMs and AI tools. ## Overview - [API introduction](https://sendtern.com/docs/api-introduction.md): Base URL, authentication, formats and conventions. ## Emails - [Send email](https://sendtern.com/docs/api-send-email.md): Queue a transactional email for delivery. - [Retrieve email](https://sendtern.com/docs/api-get-email.md): Get one email with its full event history. - [List emails](https://sendtern.com/docs/api-list-emails.md): Page through sent emails, newest first. - [Email stats](https://sendtern.com/docs/api-email-stats.md): Daily sent, delivered and bounced counts. ## Domains - [Create domain](https://sendtern.com/docs/api-create-domain.md): Add a domain and get its DNS records. - [List domains](https://sendtern.com/docs/api-list-domains.md): All domains in the workspace. - [Retrieve domain](https://sendtern.com/docs/api-get-domain.md): One domain with its records. - [Verify domain](https://sendtern.com/docs/api-verify-domain.md): Check the DNS records now. - [Delete domain](https://sendtern.com/docs/api-delete-domain.md): Remove a domain from the workspace. ## API keys - [Create API key](https://sendtern.com/docs/api-create-api-key.md): Create a key. The token is returned once. - [List API keys](https://sendtern.com/docs/api-list-api-keys.md): All keys, without their tokens. - [Revoke API key](https://sendtern.com/docs/api-delete-api-key.md): Revoke a key immediately.