TrivSend developer guide

Everything an application needs to send email through TrivSend, receive it, and react to what happens after. Written for people and for AI coding assistants: every request and response below is the real shape the API returns.

Quick start

Four steps from zero to a delivered email.

  1. Create an account at https://app.trivsend.com/signup and confirm your email address. New accounts are reviewed before they can send to real recipients; you can set everything up, and send with a test key, in the meantime.
  2. Add your sending domain under Domains. Use a subdomain such as notify.example.com, so transactional reputation stays separate from your people's mail. Publish the DNS records it shows, then click Verify. See Domains and DNS.
  3. Create an API key under API keys. Choose Sending access for an app that only sends. The key (ts_...) is shown once; store it as a secret, for example TRIVSEND_API_KEY.
  4. Send:
bash
curl -X POST https://api.trivsend.com/emails \
  -H "Authorization: Bearer $TRIVSEND_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "from": "Acme <noreply@notify.example.com>",
    "to": "user@example.com",
    "subject": "Your sign-in code",
    "html": "<p>Your code is <strong>482913</strong></p>",
    "text": "Your code is 482913"
  }'
json
{ "id": "3f2a1c9e-7b4d-4e8a-9c1f-2d6b8a0e5f71" }

Using a framework? See Framework quickstarts for Next.js, Django, Laravel and WordPress, and React Email.

A 200 with an id means TrivSend accepted the email and queued it. Delivery happens in the background; follow it with GET /emails/:id or webhooks.

Authentication

Every request carries an API key as a bearer token:

text
Authorization: Bearer ts_xxxxxxxxxxxxxxxxxxxxxxxx
Key typePrefixCan do
Full accessts_Everything in this guide
Sending accessts_POST /emails, POST /emails/batch, POST /validations, GET /usage. Can be limited to one domain with domain_id
Testts_test_Sending access, but nothing is delivered: every email is accepted, logged and simulated. See Testing

Rules for keys:

json
{ "name": "production", "permission": "sending_access", "allowed_ips": ["203.0.113.10", "10.20.0.0/16"] }

Sending email

POST /emails

Send one email.

FieldTypeRequiredNotes
fromstringyes*"Name <addr@domain>" or "addr@domain". The domain must be verified in your account
tostring or string[]yesUp to 50 recipients across to, cc and bcc
cc, bccstring or string[]no
reply_tostring or string[]no
subjectstringyes*Up to 998 characters
htmlstringone of*HTML body
textstringone of*Plain-text body. Send both for the best inbox placement
headersobjectnoExtra headers, e.g. {"X-Entity-Ref-ID": "123"}. From, To, Subject, Message-ID, Date and similar are set by TrivSend
tags{name, value}[]noUp to 50. Letters, numbers, _ and - only. Searchable and included in webhooks
attachmentsobject[]noUp to 20. See Attachments
scheduled_atstringnoSend later. See Scheduling
template{id, variables}noSend a hosted template instead of html/text. See Templates
priority"high", "normal" or "low"noTrivSend extension. Order in the delivery queue; see Priority. Default normal
expires_atstringnoTrivSend extension. ISO 8601 time with timezone after which the email must not be sent; see Expiry for OTPs

* With template, from and subject may come from the template instead, and html/text must not be sent.

Optional request header: Idempotency-Key. See Idempotency.

Response 200:

json
{ "id": "3f2a1c9e-7b4d-4e8a-9c1f-2d6b8a0e5f71" }

POST /emails/batch

Send up to 100 emails in one request. The body is a JSON array of POST /emails objects. Either all of them are accepted or none are: a validation error in any one rejects the whole batch.

bash
curl -X POST https://api.trivsend.com/emails/batch \
  -H "Authorization: Bearer $TRIVSEND_API_KEY" \
  -H "Content-Type: application/json" \
  -d '[
    {"from": "Acme <noreply@notify.example.com>", "to": "a@example.com", "subject": "Hi A", "text": "Hello"},
    {"from": "Acme <noreply@notify.example.com>", "to": "b@example.com", "subject": "Hi B", "text": "Hello"}
  ]'
json
{ "data": [ { "id": "..." }, { "id": "..." } ] }

Batch emails default to priority: "low", so a large batch doesn't hold up your one-off sends. Set priority on an item to change it.

Priority

When many emails are waiting, high goes out before normal, and normal before low; within a level, first in, first out. Use high for sign-in codes and password resets, and low for bulk work such as invoice runs. If your HTTP client or library drops fields it doesn't know, send the header X-TrivSend-Priority: high in headers instead; it works the same through the SMTP relay, and TrivSend removes it before sending. Priority only changes the order while there is a queue: it doesn't skip rate limits, quotas or retries. Marketing broadcasts have their own queue and never delay transactional mail.

Expiry for OTPs

A sign-in code that arrives after it stopped working only confuses people. Set expires_at and TrivSend never sends the email after that time:

json
{ "from": "Acme <noreply@notify.example.com>", "to": "asha@example.com", "subject": "Your code: 482913", "text": "Your code is 482913. It expires in 5 minutes.", "expires_at": "2026-11-18T10:05:00+05:30" }
js
// In your webhook handler
if (event.type === "email.failed" && event.data.failed.expired) {
  await sendSms(event.data.to[0], "Your code is ...");
}

GET /emails/:id shows expires_at. How fast your emails go out is in Stats.

Check before sending

POST /emails/check takes the same body as POST /emails and sends nothing. It returns what would hurt the email, worst first:

json
{
  "object": "email_check",
  "score": 8,
  "verdict": "improve",
  "issues": [
    { "code": "no_text_part", "severity": "warning", "message": "There is no plain-text version. ..." },
    { "code": "subject_caps", "severity": "warning", "message": "The subject is mostly capital letters, ..." }
  ]
}

score starts at 10; a problem costs 3 and a warning 1. verdict is good, improve or fix (any problem). In the dashboard, Emails → Send a test → Check first does the same.

Code examples

Node.js (18 or later, no packages needed):

js
const res = await fetch("https://api.trivsend.com/emails", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.TRIVSEND_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": `welcome-${user.id}`,
  },
  body: JSON.stringify({
    from: "Acme <noreply@notify.example.com>",
    to: user.email,
    subject: "Welcome to Acme",
    html: "<h1>Welcome!</h1>",
    text: "Welcome!",
    tags: [{ name: "category", value: "welcome" }],
  }),
});
const body = await res.json();
if (!res.ok) throw new Error(`TrivSend ${res.status} ${body.name}: ${body.message}`);
console.log("queued", body.id);

Python (requests):

python
import os, requests

res = requests.post(
    "https://api.trivsend.com/emails",
    headers={
        "Authorization": f"Bearer {os.environ['TRIVSEND_API_KEY']}",
        "Idempotency-Key": f"welcome-{user_id}",
    },
    json={
        "from": "Acme <noreply@notify.example.com>",
        "to": user_email,
        "subject": "Welcome to Acme",
        "html": "<h1>Welcome!</h1>",
        "text": "Welcome!",
    },
    timeout=15,
)
body = res.json()
if not res.ok:
    raise RuntimeError(f"TrivSend {res.status_code} {body['name']}: {body['message']}")
print("queued", body["id"])

PHP:

php
$ch = curl_init("https://api.trivsend.com/emails");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("TRIVSEND_API_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "from" => "Acme <noreply@notify.example.com>",
        "to" => $email,
        "subject" => "Welcome to Acme",
        "html" => "<h1>Welcome!</h1>",
    ]),
]);
$body = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status !== 200) throw new Exception("TrivSend $status {$body['name']}: {$body['message']}");

Oracle APEX / PL/SQL (APEX_WEB_SERVICE; the database needs an ACL and a wallet that trusts Let's Encrypt for api.trivsend.com):

sql
declare
  l_body     clob;
  l_response clob;
begin
  select json_object(
           'from'    value 'Acme <noreply@notify.example.com>',
           'to'      value :P1_EMAIL,
           'subject' value 'Your report is ready',
           'html'    value '<p>Hello</p>'
           returning clob)
    into l_body
    from dual;

  apex_web_service.g_request_headers.delete;
  apex_web_service.g_request_headers(1).name  := 'Authorization';
  apex_web_service.g_request_headers(1).value := 'Bearer ' || :TRIVSEND_API_KEY;
  apex_web_service.g_request_headers(2).name  := 'Content-Type';
  apex_web_service.g_request_headers(2).value := 'application/json';

  l_response := apex_web_service.make_rest_request(
    p_url         => 'https://api.trivsend.com/emails',
    p_http_method => 'POST',
    p_body        => l_body);

  if apex_web_service.g_status_code <> 200 then
    raise_application_error(-20001, 'TrivSend: ' || dbms_lob.substr(l_response, 2000, 1));
  end if;
end;

Attachments

json
"attachments": [
  {
    "filename": "invoice-1042.pdf",
    "content": "JVBERi0xLjQKJ...",
    "content_type": "application/pdf"
  },
  {
    "filename": "logo.png",
    "content": "iVBORw0KGgo...",
    "content_id": "logo"
  }
]
json
"attachments": [{ "filename": "invoice-1042.pdf", "path": "https://files.example.com/invoices/1042.pdf" }]

Idempotency

Networks fail after the server has acted. To retry safely, send an Idempotency-Key header (up to 256 characters) that is unique per logical email, for example otp-<request id> or invoice-<invoice id>. A repeat request with the same key returns the original email's id and sends nothing new. Keys are scoped to your account.

Scheduling

Set scheduled_at to send later, up to 30 days ahead:

A scheduled email has status scheduled until it goes out. Change or cancel it:

bash
# Reschedule
curl -X PATCH https://api.trivsend.com/emails/$ID \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"scheduled_at": "in 1 hour"}'

# Cancel
curl -X POST https://api.trivsend.com/emails/$ID/cancel -H "Authorization: Bearer $KEY"

Both return { "object": "email", "id": "..." } and need a full-access key. Only emails that are still scheduled can be changed.

Check an email

GET /emails/:id (full access):

json
{
  "object": "email",
  "id": "3f2a1c9e-7b4d-4e8a-9c1f-2d6b8a0e5f71",
  "from": "Acme <noreply@notify.example.com>",
  "to": ["user@example.com"],
  "cc": [],
  "bcc": [],
  "reply_to": [],
  "subject": "Your sign-in code",
  "html": "<p>Your code is <strong>482913</strong></p>",
  "text": "Your code is 482913",
  "tags": [{ "name": "category", "value": "otp" }],
  "status": "sent",
  "last_event": "sent",
  "message_id": "<3f2a1c9e-...@notify.example.com>",
  "template_id": null,
  "test": false,
  "priority": "normal",
  "expires_at": null,
  "scheduled_at": null,
  "created_at": "2026-10-22T09:14:03.120Z",
  "sent_at": "2026-10-22T09:14:04.501Z"
}
statusMeaning
scheduledWaiting for scheduled_at
queued, sendingAccepted, being delivered
sentThe recipient's mail server accepted it
bouncedThe recipient's server rejected it (after it was sent)
failedCould not be delivered after all retries, or expired before it could be sent (expires_at)
suppressedNot sent: every recipient is on your suppression list
canceledA scheduled email you canceled

last_event is the latest thing that happened, which can be newer than the status: delivery_delayed, bounced, complained, opened or clicked.

sent means the receiving server accepted the message. Whether it lands in the inbox or in spam is decided by the receiver; good DNS, consistent sending and clean lists are what move that.

Why it bounced or failed

GET /emails/:id/events (full access, a TrivSend extension) lists everything that happened to the email, oldest first, with the reason when there is one. The email's page in the dashboard shows the same under Delivery.

json
{
  "object": "list",
  "data": [
    { "object": "email_event", "id": "…", "type": "queued", "created_at": "2026-11-06T04:17:02.311Z", "reason": null, "details": {} },
    { "object": "email_event", "id": "…", "type": "sent", "created_at": "2026-11-06T04:17:03.020Z", "reason": "250 2.0.0 Ok: queued as 4XkL9", "details": { "response": "250 2.0.0 Ok: queued as 4XkL9", "accepted": ["user@example.com"] } },
    {
      "object": "email_event", "id": "…", "type": "bounced", "created_at": "2026-11-06T04:17:09.874Z",
      "reason": "5.1.1 · 550 5.1.1 <user@example.com>: Recipient address rejected: User unknown",
      "details": { "recipient": "user@example.com", "kind": "hard", "status": "5.1.1", "diagnostic": "550 5.1.1 <user@example.com>: Recipient address rejected: User unknown", "remote_mta": "mx.example.com" }
    }
  ]
}

Each event also has advice when TrivSend recognises the problem: what it means and what to do, in plain English. side says whose problem it is: recipient (the address or mailbox), sender (your domain setup or content, which you can fix), trivsend (our sending IP or servers, which we're alerted to and fix) or temporary (retried, or nothing to do). code is stable, for your own logic. When TrivSend can't tell, advice is null.

json
"advice": {
  "code": "dmarc_failed",
  "side": "sender",
  "summary": "The receiver rejected it because it failed DMARC: neither SPF nor DKIM lined up with the domain in your From address.",
  "fix": "Open the domain in TrivSend and click Verify: every record must show as verified. …"
}

The codes are address_not_found, domain_not_found, mailbox_full, message_too_large, dmarc_failed, spf_failed, dkim_failed, spam_content, rate_limited, ip_blocklisted, reverse_dns and temporary. The email.bounced webhook carries the same in bounce.advice. The email's page in the dashboard shows it as What this means / What to do.

type is one of scheduled, queued, sent, deferred (a temporary error; TrivSend retries), delayed (the receiving side is still trying), bounced, bounce_unparsed (a bounce TrivSend couldn't read; reason is the start of its text), failed, suppressed, complained, opened, clicked, unsubscribed or canceled. For a bounce, details.kind is hard (the address doesn't exist; it's added to your suppression list), soft (mailbox full or similar), block (refused by policy, often spam filtering or a blocklist) or undetermined.

Export

GET /emails/export (full access) returns the log as a CSV file, newest first, with the same filters as GET /emails below, up to 100,000 rows; narrow the dates for more. The columns are: id, created and sent times, status, from, to, cc, bcc, subject, tags, priority, stream, test, expires_at and message_id. Emails → Export CSV in the dashboard exports the current search. GET /audit-log/export does the same for the audit log (owners and admins).

GET /emails (full access) returns the newest first and takes these filters, which combine:

QueryExample
recipientuser@example.com (matches to, cc and bcc)
statussent,bounced
tagcategory=otp
subject, frompartial, case-insensitive
streamtransactional or marketing
testtrue or false
created_after, created_before2026-10-01T00:00:00Z
bash
curl -H "Authorization: Bearer $KEY" \
  "https://api.trivsend.com/emails?recipient=user@example.com&status=bounced&limit=20"

Pagination

Every list endpoint pages the same way:

json
{ "object": "list", "data": [ ... ], "has_more": true }

Keep calling with after set to the last item's id while has_more is true.

Errors

Errors always have this shape:

json
{ "statusCode": 403, "name": "invalid_from_address", "message": "The example.com domain is not verified. Verify its DNS records first." }

Branch on name; show message to developers, not end users.

StatusnameWhat to do
401missing_api_keySend the Authorization: Bearer header
403invalid_api_keyThe key is wrong or revoked
401restricted_api_keyA sending-access key called a full-access endpoint, or used another domain
403invalid_from_addressAdd and verify the from domain
403account_pending_reviewYour account is in review: most are approved within a few minutes of verifying your email, some need a person (usually within one working day). Use a test key meanwhile
403tenant_paused, tenant_suspendedSending is stopped for the account. A pause for high bounces or complaints can be resumed by an owner from the dashboard once every 30 days; otherwise contact support
404not_foundWrong id, or it belongs to another account
422validation_errorThe message names the field and the problem
429rate_limit_exceededToo many requests per second; retry after a short pause
429daily_quota_exceeded, monthly_quota_exceededPlan limit reached; resets at midnight UTC or on the 1st
500application_errorRetry with the same Idempotency-Key

Retrying

Retry on network errors, 429 rate_limit_exceeded and 5xx, with exponential backoff (for example 1 s, 2 s, 4 s, 8 s) and the same Idempotency-Key, so a retry never sends twice. Don't retry other 4xx errors; fix the request.

Request log

Every request made with an API key is logged for 14 days: method, path (without the query string), status, time taken, the error name and message if it failed, the key, and the caller's IP and user agent. Request bodies aren't kept. See it in the dashboard under API keys → Request log, or with GET /request-logs?status=error&api_key_id=... (full access). It's the quickest way to see why an integration's calls fail.

Rate limits and quotas

Each account has a requests-per-second limit and daily and monthly email quotas, set by its plan. Quotas count emails that can reach a real mailbox; test keys and simulator addresses are free. Check them at any time:

bash
curl -H "Authorization: Bearer $KEY" https://api.trivsend.com/usage
json
{
  "object": "usage",
  "plan": { "slug": "starter", "name": "Starter" },
  "status": "active",
  "emails": {
    "daily":   { "used": 132,  "limit": 1000,  "resets_at": "2026-10-23T00:00:00.000Z" },
    "monthly": { "used": 4210, "limit": 30000, "resets_at": "2026-11-01T00:00:00.000Z" }
  }
}

(Shortened; the response also reports contacts, domains and bounce/complaint counts.)

The account's owners and admins get an email when a daily or monthly quota reaches 80% and when it is reached, so you can ask for a bigger plan before sends are refused. They are also emailed if the bounce or complaint rate gets close to the level where sending is paused, and if it is paused. Once you've fixed the cause (usually by removing addresses that bounce and checking how the list was collected), an owner or admin can resume sending from the overview in the dashboard, once every 30 days. Bounces and complaints are then counted afresh from that moment. A second pause within 30 days is reviewed by our team.

Changing your plan

GET /plans lists the plans you can move to, with their limits (null means unlimited) and monthly price in rupees before GST (0 for Free, null for plans given on request). Current prices: trivsend.com/pricing.

json
{
  "object": "list",
  "data": [
    {
      "object": "plan",
      "slug": "starter",
      "name": "Starter",
      "limits": { "emails_per_day": 2000, "emails_per_month": 50000, "requests_per_second": 10, "domains": 5, "contacts": 10000 },
      "price_monthly_inr": 999
    }
  ]
}

The Free plan is open to everyone. The listed prices are for customers in India; outside India, write to billing@trivsend.com for a price. Until online payment is switched on, buy a plan by asking for it under Settings → Plan or writing to billing@trivsend.com: we send an invoice to pay by bank transfer or UPI, and the plan applies, with its paid-until date, when the payment arrives. Once online payment is on, plans are bought in the dashboard under Settings → Billing, for 1, 3, 6 or 12 months (12 cost the price of 10), through Cashfree (UPI, cards, net banking, wallets). Account owners and team members with the billing role can pay; each payment has an invoice on the same page, with the credit note under it if any of it was refunded (refund and credit_note in GET /billing/invoices/:id). Renewing extends your period; moving to a bigger plan starts now and credits the unused days of the current one. A dedicated sending IP (₹2,500 a month) is an add-on: ask for it on the same page, and pay for it once it is set up. When a paid period ends, the account moves to the free plan's limits, with reminders 7 days and 1 day before.

Moving to the free plan is done under Settings → Plan by an account owner or a team member with the billing role. It applies at once, or when a paid period ends if one is running. Plans without a price (shown as "On request") are asked for on the same page, with an optional note: the TrivSend team reviews it and you get an email when the plan changes (or if it stays the same). The new limits apply to your next request. GET /account shows plan and, while a request is pending, requested_plan and plan_requested_at.

What your plan includes

Besides sending limits, plans differ in a few extras. GET /account shows yours in features:

json
"features": { "log_days": 30, "max_members": null, "content_retention_control": false, "max_client_accounts": 0, "signed_dpa": false, "support_reply_hours": 24 }
FreeStarterGrowthPro
Email log kept (log_days)7 days30 days90 days90 days
People on the account1anyanyany
Choose content retentionnonoyesyes
Client accounts00525

Free accounts created before 19 November 2026 keep a 90-day log and any number of people until 1 January 2027. Inviting past the limit answers 403 plan_limit_exceeded.

Client accounts for agencies

On Growth and Pro, an owner creates a separate account for each client under Settings → Client accounts. Each has its own domains, API keys, limits, log and reputation, so one client's bad list never pauses another's mail.

Weekly report

Every Monday morning (India time), the owners and admins of an account that sent mail that week get one email:

Turn it off under Settings → Account, or with PATCH /account {"weekly_report": false}.

Your data

TrivSend stores your account's data in India (Oracle Cloud, Mumbai); GET /account shows data_location. For the email you send, we are your data processor under India's DPDP Act. The Data Processing Agreement sets out what we do with it, and is part of every account.

Email content (bodies and attachments of sent mail, and received mail; not subject lines) is kept 30 days by default. An owner can shorten that under Settings → Account in the dashboard:

Deliverability

GET /deliverability?days=7 (full access; days from 1 to 30, default 7) answers "is my mail getting through, and if not, why?". The dashboard's Deliverability page shows the same.

Numbers cover emails created in the window, with the bounces and complaints they got afterwards; test mode and simulator addresses are left out.

json
{
  "object": "deliverability",
  "days": 7,
  "status": "problem",
  "issues": [{ "severity": "problem", "title": "Gmail / Google Workspace: 40.0% bounced", "detail": "8 blocked out of 20 sent. The top reasons below say why." }],
  "totals": { "sent": 120, "bounced": 9, "blocked": 8, "complained": 0, "bounce_rate": 0.075, "complaint_rate": 0 },
  "providers": [{ "provider": "gmail", "name": "Gmail / Google Workspace", "sent": 20, "bounced": 8, "blocked": 8, "hard_bounced": 0, "soft_bounced": 0, "complained": 0, "bounce_rate": 0.4, "status": "problem", "top_domains": [{ "domain": "gmail.com", "sent": 14 }] }],
  "top_reasons": [{ "status": "5.7.25", "kind": "block", "diagnostic": "The IP address sending this message does not have a PTR record setup…", "count": 8, "providers": ["Gmail / Google Workspace"], "hint": "The sending IP has no reverse DNS (PTR). Gmail and Yahoo require it." }],
  "sending_ips": { "hostname": "mail.trivsend.com", "ip_pool": null, "error": null, "ips": [{ "ip": "130.210.63.68", "ptr": ["mail.trivsend.com"], "forward_confirmed": true, "matches_hostname": true, "blocklists": [{ "name": "SpamCop", "zone": "bl.spamcop.net", "listed": false }] }] },
  "domains": [ … ]
}

To try a send without writing code, use Emails → Send a test in the dashboard: pick a From address on a verified domain, send to your own Gmail, Yahoo or Outlook address (or a simulator address), and the email's page shows its delivery history.

Stats

GET /stats?start=YYYY-MM-DD&end=YYYY-MM-DD&stream=transactional|marketing (full access, up to 92 days, default the last 30) returns daily counts (sent, failed, suppressed, bounced, complained, opened, clicked) and their totals and rates. The dashboard's Stats page charts them.

It also has time_to_send: how fast transactional emails went from TrivSend accepting them to our mail server accepting them. Scheduled and test emails are left out. This is not the time to the inbox, which no sender can measure.

json
"time_to_send": { "emails": 1840, "p50_ms": 640, "p95_ms": 2300, "within_5s_rate": 0.992 }

With stream=marketing it is null: broadcasts are paced on purpose.

Domains and DNS

Check any domain's MX, SPF, DKIM and DMARC for free at trivsend.com/tools/domain-check, no account needed.

You can only send from domains you have added and verified. Add one in the dashboard or with POST /domains {"name": "notify.example.com"}; the response lists the DNS records to publish:

RecordTypeNameValue
DKIMTXTtrivsend._domainkey.notify.example.comv=DKIM1; k=rsa; p=... (unique per domain)
Return pathMXbounces.notify.example.commail.trivsend.com, priority 10
SPFTXTbounces.notify.example.comv=spf1 include:_spf.trivsend.com ~all
DMARC (recommended)TXT_dmarc.notify.example.comv=DMARC1; p=none; rua=mailto:dmarc@feedback.trivsend.com;

Then verify with Verify in the dashboard or POST /domains/:id/verify. The domain's status becomes verified once DKIM, the return-path MX and SPF are found. DNS changes can take a few minutes to an hour to appear.

Notes:

Automatic setup

You don't have to type the records by hand. On the domain's page in the dashboard, TrivSend shows where your DNS is hosted and how to add the records there.

The token is used for that one request and never stored. TrivSend only adds records:

With the API, call POST /domains/:id/dns/cloudflare {"api_token": "..."}. The response lists each record as created, updated, already_set or conflict (with the reason), and includes the domain after verifying.

All three need a full-access key.

Domain settings, with PATCH /domains/:id:

FieldEffect
open_tracking, click_trackingtrue/false. Off by default
tracking_subdomaine.g. "links": tracked links use links.notify.example.com instead of a TrivSend host. Add the CNAME it shows (to track.trivsend.com) and verify. null removes it
inboundtrue to receive mail. See Receiving email

DMARC reports

Mailbox providers send a daily report of everything sent as your domain to the rua address in its DMARC record. With TrivSend's address there, TrivSend reads the reports for you:

A failing source marked signed_by_trivsend is your own mail that broke on the way, so check the domain's records with Verify. Any other failing source is a service you haven't set up SPF and DKIM for (a CRM, a helpdesk), or someone spoofing you. p=quarantine and p=reject stop spoofing.

json
{
  "object": "dmarc_report",
  "id": "8a1c…",
  "reporter": "google.com",
  "domain": "notify.example.com",
  "date_begin": "2026-10-25T00:00:00.000Z",
  "date_end": "2026-10-25T23:59:59.000Z",
  "messages": 1250,
  "passed": 1247,
  "failed": 3,
  "failing_sources": [{ "source_ip": "198.51.100.7", "count": 3, "signed_by_trivsend": false, "disposition": "none", "header_from": "notify.example.com" }],
  "records": [ … ]
}
json
{
  "object": "list",
  "has_more": false,
  "data": [ … ],
  "readiness": { "policy": "none", "next": "quarantine", "ready": true, "detail": "Ready for p=quarantine: 99.8% of 4,210 messages passed over 15 days. Change p=none to p=quarantine in the _dmarc TXT record." }
}

Reports start about a day after the record is in place. Providers only send them to an address on another domain when that domain allows it; TrivSend does, for every domain.

Templates

Store an email once, send it by id or alias with different variables. Create templates in the dashboard (Templates) or with POST /templates:

json
{
  "name": "Sign-in code",
  "alias": "otp",
  "from": "Acme <noreply@notify.example.com>",
  "subject": "Your code is {{{CODE}}}",
  "html": "<p>Hi {{{NAME|there}}}, your code is <strong>{{{CODE}}}</strong>.</p>",
  "variables": [{ "key": "CODE", "type": "string" }, { "key": "NAME", "type": "string", "fallback_value": "there" }]
}

Publish it (POST /templates/otp/publish, or Publish in the dashboard), then send:

json
{
  "to": "user@example.com",
  "template": { "id": "otp", "variables": { "CODE": "482913", "NAME": "Asha" } }
}

Ready-made templates

TrivSend has a library of ready-made transactional templates:

Each has a plain-text part, works on phones and in dark mode, and is far under Gmail's clipping size.

bash
# The library (without the HTML)
curl https://api.trivsend.com/templates/gallery -H "Authorization: Bearer $KEY"

# Add one to your account, published, under the alias "otp" (then otp-2, ...), or your own alias
curl -X POST https://api.trivsend.com/templates/gallery/otp -H "Authorization: Bearer $KEY" \
  -H "Content-Type: application/json" -d '{}'

Then send it by alias:

json
{ "from": "Acme <noreply@notify.example.com>", "to": "asha@example.com", "template": { "id": "otp", "variables": { "CODE": "482913", "PRODUCT": "Acme" } }, "expires_at": "2026-11-18T10:05:00+05:30" }

The variables are listed with each template (CODE, PRODUCT, MINUTES, LINK, NAME...). Most have defaults. BRAND_COLOR (for example #e11d48) colours the button, the card's top edge and the mark beside your product name; it defaults to indigo. The templates work in light and dark mode, and their buttons show in Outlook too. In the dashboard: Templates → Ready-made templates → Add. Once added, it's your template to edit.

Preview and versions

POST /templates/:idOrAlias/preview renders a template with test values without sending anything:

json
{ "version": "draft", "variables": { "NAME": "Asha", "CODE": "482913" } }

version is "draft" (the default), "published" or a version number. The response has subject, html, text and missing_variables: placeholders with no value and no fallback, which a real send would refuse. The dashboard shows the preview next to the editor, at desktop or phone width.

Every publish is kept as a numbered version, and POST /templates/:idOrAlias/publish returns its version. GET /templates/:idOrAlias/versions lists them newest first (live marks the one sends use), GET /templates/:idOrAlias/versions/:version returns one, and POST /templates/:idOrAlias/versions/:version/restore copies it into the draft. Restoring doesn't change what's sent until you publish again.

Webhooks

Webhooks tell your app what happened after a send, without polling. Create one in the dashboard (Webhooks) or with the API:

bash
curl -X POST https://api.trivsend.com/webhooks \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"endpoint": "https://example.com/hooks/trivsend", "events": ["email.sent", "email.bounced", "email.complained"]}'
json
{ "object": "webhook", "id": "...", "signing_secret": "whsec_..." }

Store signing_secret; it is shown once (rotate it with POST /webhooks/:id/signing-secret/rotate).

Events

EventWhen
email.scheduledAn email was scheduled
email.sentThe recipient's server accepted it
email.delivery_delayedA temporary failure; TrivSend keeps retrying
email.bouncedThe address doesn't exist or rejected it; the address is now suppressed
email.complainedThe recipient marked it as spam; the address is now suppressed
email.failedGave up after all retries, or expires_at passed first (failed.expired: true)
email.suppressedNot sent because the recipient is suppressed
email.opened, email.clickedWith open/click tracking on
email.receivedInbound mail arrived. See Receiving email
contact.created, contact.updated, contact.deleted, contact.topics.updatedMarketing contacts changed
domain.created, domain.updated, domain.deletedDomains changed
suppression.added, suppression.removedThe suppression list changed
topic.created, topic.updated, topic.deletedTopics changed

Payload:

json
{
  "type": "email.bounced",
  "created_at": "2026-10-22T09:15:10.000Z",
  "data": {
    "email_id": "3f2a1c9e-7b4d-4e8a-9c1f-2d6b8a0e5f71",
    "created_at": "2026-10-22T09:14:03.120Z",
    "message_id": "<3f2a1c9e-...@notify.example.com>",
    "from": "Acme <noreply@notify.example.com>",
    "to": ["user@example.com"],
    "subject": "Your sign-in code",
    "tags": { "category": "otp" },
    "bounce": {
      "type": "Permanent",
      "subType": "hard",
      "message": "550 5.1.1 user unknown",
      "status": "5.1.1",
      "recipient": "user@example.com"
    }
  }
}

Verify the signature

Every request is signed with the Standard Webhooks scheme. The headers are webhook-id, webhook-timestamp and webhook-signature (also sent as svix-id, svix-timestamp, svix-signature). Any Standard Webhooks or Svix library verifies them. Without a library:

  1. Take the raw request body, exactly as received, before any JSON parsing.
  2. Compute HMAC-SHA256 over <webhook-id>.<webhook-timestamp>.<raw body>, keyed with the base64-decoded part of the secret after whsec_.
  3. Base64 the result and compare it with each v1,<signature> entry in webhook-signature (space-separated), in constant time.
  4. Reject timestamps more than 5 minutes from now, to stop replays.

Node.js (Express):

js
import crypto from "node:crypto";
import express from "express";

const secret = Buffer.from(process.env.TRIVSEND_WEBHOOK_SECRET.replace(/^whsec_/, ""), "base64");

app.post("/hooks/trivsend", express.raw({ type: "application/json" }), (req, res) => {
  const id = req.header("webhook-id");
  const timestamp = req.header("webhook-timestamp");
  const signatures = (req.header("webhook-signature") ?? "").split(" ");
  if (!id || !timestamp || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return res.sendStatus(400);

  const expected = crypto.createHmac("sha256", secret).update(`${id}.${timestamp}.${req.body}`).digest();
  const valid = signatures.some((s) => {
    const given = Buffer.from(s.replace(/^v1,/, ""), "base64");
    return given.length === expected.length && crypto.timingSafeEqual(given, expected);
  });
  if (!valid) return res.sendStatus(401);

  const event = JSON.parse(req.body.toString("utf8"));
  // Deduplicate on webhook-id: a retried delivery has the same id.
  handle(event).then(() => res.sendStatus(200), () => res.sendStatus(500));
});

Python (Flask):

python
import base64, hashlib, hmac, os, time
from flask import Flask, request, abort

secret = base64.b64decode(os.environ["TRIVSEND_WEBHOOK_SECRET"].removeprefix("whsec_"))

@app.post("/hooks/trivsend")
def trivsend_hook():
    msg_id = request.headers.get("webhook-id", "")
    ts = request.headers.get("webhook-timestamp", "0")
    if abs(time.time() - int(ts)) > 300:
        abort(400)
    body = request.get_data()  # raw bytes
    expected = base64.b64encode(hmac.new(secret, f"{msg_id}.{ts}.".encode() + body, hashlib.sha256).digest()).decode()
    given = [s.split(",", 1)[-1] for s in request.headers.get("webhook-signature", "").split()]
    if not any(hmac.compare_digest(expected, g) for g in given):
        abort(401)
    event = request.get_json()
    # ... handle event["type"], deduplicate on msg_id
    return "", 200

Delivery and retries

Testing an endpoint

POST /webhooks/:id/test (optional body {"type": "email.bounced"}; default the webhook's first event) sends a sample event to the endpoint right away and returns what it answered. It works while the webhook is disabled, isn't retried, and is signed like a real event. The payload has the real shape with obviously fake ids and "test": true at the top, so your handler can skip it.

json
{ "object": "webhook_test", "ok": false, "response_status": 500, "response_body": "TypeError: ...", "error": "HTTP 500: TypeError: ...", "duration_ms": 84, "event": { "id": "...", "status": "failed" } }

The dashboard's webhook page has the same as Send a test event.

Receiving email

Turn on inbound for a domain (PATCH /domains/:id {"inbound": true}, or the switch on the domain's page), then add the MX record it shows:

TypeNameValue
MXinbound.notify.example.commail.trivsend.com, priority 10

After verification, mail to any address at inbound.notify.example.com (for example support@inbound.notify.example.com or reply+ticket-42@inbound.notify.example.com) is stored and sent to your email.received webhooks. Messages can be up to 25 MB.

The webhook carries the metadata; fetch the body and attachments with the API:

bash
curl -H "Authorization: Bearer $KEY" https://api.trivsend.com/emails/receiving/$EMAIL_ID
json
{
  "object": "email",
  "id": "...",
  "from": "Asha <asha@example.org>",
  "to": ["support@inbound.notify.example.com"],
  "cc": [],
  "reply_to": [],
  "subject": "Re: Ticket 42",
  "message_id": "<CAF...@mail.gmail.com>",
  "created_at": "2026-10-22T10:01:00.000Z",
  "rcpt_to": ["support@inbound.notify.example.com"],
  "html": "<div>Thanks, that fixed it.</div>",
  "text": "Thanks, that fixed it.",
  "headers": { "in-reply-to": "<...>" },
  "attachments": [
    { "id": "...", "filename": "screenshot.png", "content_type": "image/png", "content_disposition": "attachment", "content_id": null, "size": 48213 }
  ]
}

Download an attachment with GET /emails/receiving/:id/attachments/:attachmentId; content is base64. List everything received with GET /emails/receiving.

Tip: to route replies to the right record, send with reply_to: "reply+ticket-42@inbound.notify.example.com" and read the part after + from rcpt_to when the reply arrives.

Validating addresses

Check an address before you store it or send to it, for example on a sign-up form:

bash
curl -X POST https://api.trivsend.com/validations \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"email": "asha@gmial.com"}'
json
{
  "object": "validation",
  "email": "asha@gmial.com",
  "result": "valid",
  "reason": "accepted",
  "did_you_mean": "asha@gmail.com",
  "checks": { "syntax": true, "mail_server": true, "disposable": false, "role": false, "free": false, "suppressed": false }
}
resultreasonSuggested handling
validacceptedAccept. If did_you_mean is set, ask "Did you mean ...?"
riskydisposable, role_addressAccept or warn, your choice
invalidinvalid_syntax, no_mail_server, suppressedReject or ask for another address
unknowndns_errorAccept; try again later

POST /validations/batch takes {"emails": [...]} (up to 100) and returns { "object": "list", "data": [...] }. Sending-access keys may call both. Validation checks syntax, DNS and lists; it never connects to the mailbox, so valid means "this domain takes mail and nothing marks it risky", not "this inbox exists".

Suppressions

TrivSend never sends to an address on your suppression list. Hard bounces, spam complaints and unsubscribes are added automatically; an email to only suppressed recipients gets status suppressed.

RequestPurpose
GET /suppressions?origin=bounceList (origins: bounce, complaint, unsubscribe, manual)
POST /suppressions {"email": "..."}Block an address yourself
GET /suppressions/:idOrEmailIs this address suppressed, and why
DELETE /suppressions/:idOrEmailRemove one, for example after a user fixed their mailbox
POST /suppressions/batch/add, /batch/removeUp to 100 at once

Remove a complaint suppression only if the person asked for your mail again.

Testing without sending

Two tools, usable together:

Simulator addresses work with any key and never leave TrivSend:

Send toResult
delivered@simulator.trivsend.comsent
bounced@simulator.trivsend.comsent, then a hard bounce and an email.bounced webhook
complained@simulator.trivsend.comsent, then a complaint and an email.complained webhook

Add a label to tell tests apart: bounced+signup-test@simulator.trivsend.com. Simulated events never add suppressions and don't count toward quotas.

Test keys (ts_test_..., created with Test under API keys or POST /api-keys {"name": "ci", "test": true}) accept, log and simulate every email, even to real addresses, and nothing is delivered. They work before your domain is verified and while your account is in review, which makes them right for CI and staging.

SMTP relay

For software that can only send over SMTP (WordPress, Supabase Auth, Keycloak, Grafana, Oracle APEX instance settings, ...):

SettingValue
Hostsmtp.trivsend.com
Port587 with STARTTLS, or 465 with TLS
Usernametrivsend
Passworda TrivSend API key (sending access is enough)

The From domain must be verified, as with the API. Optional headers: X-TrivSend-Tags: category=otp, app=crm X-TrivSend-Idempotency-Key: otp-1234, X-TrivSend-Priority: high (see Priority) and X-TrivSend-Expires-At: 300 (see Expiry for OTPs). The server replies 250 OK queued as <email id>, and the email appears in the log like any API send.

Recipients work as in any mail server: every RCPT TO address receives the message, whatever the headers say. Addresses in To and Cc are logged in those roles, and envelope addresses in neither are logged as bcc and never shown to anyone. To and Cc are sent exactly as written, so Reply all from Gmail, Outlook or any client works. Each recipient is accepted or refused on its own: an address on your suppression list gets 550 5.7.1 and the others still get the message. Up to 50 recipients per message.

Node.js SDK

The trivsend package is TrivSend's official Node.js SDK: no dependencies, Node.js 18 or later, typed.

bash
npm install trivsend
TRIVSEND_API_KEY=ts_...
js
import { TrivSend } from "trivsend";

const trivsend = new TrivSend(process.env.TRIVSEND_API_KEY);
const { data, error } = await trivsend.emails.send({
  from: "Acme <noreply@notify.example.com>",
  to: "user@example.com",
  subject: "Hi",
  text: "Hello",
});
if (error) throw new Error(`${error.name}: ${error.message}`);
console.log(data.id);

Every call resolves to { data, error, headers } and never throws for an API error. Field names can be camelCase (replyTo, scheduledAt) or snake_case, as in the API. An Idempotency-Key goes in the second argument: trivsend.emails.send(email, { idempotencyKey: "welcome-42" }).

It covers emails (send, get, list, update, cancel, events), batch.send, domains, apiKeys, templates, contacts (with topics and segments), segments, topics, broadcasts, webhooks (with events), suppressions, validations and usage. For anything else, trivsend.request("GET", "/stats") calls the API directly.

trivsend.webhooks.verify({ payload, headers: { id, timestamp, signature }, webhookSecret }) checks a webhook's signature and returns the parsed event (Webhooks).

From other languages, call the API over HTTP as in Code examples: it is plain JSON with a bearer key, so any HTTP client works.

React Email

React Email components render to HTML in your app; TrivSend only ever receives html (and text). Install the renderer next to the SDK:

bash
npm install trivsend @react-email/components react react-dom
tsx
// emails/welcome.tsx
import { Body, Button, Container, Heading, Html, Text } from "@react-email/components";

export function Welcome({ name }: { name: string }) {
  return (
    <Html>
      <Body style={{ fontFamily: "sans-serif" }}>
        <Container>
          <Heading>Welcome, {name}</Heading>
          <Text>Your account is ready.</Text>
          <Button href="https://app.example.com" style={{ background: "#111", color: "#fff", padding: "10px 16px" }}>Open the app</Button>
        </Container>
      </Body>
    </Html>
  );
}
ts
import { render } from "@react-email/components";
import { TrivSend } from "trivsend";
import { Welcome } from "./emails/welcome";

const trivsend = new TrivSend(process.env.TRIVSEND_API_KEY);
const email = Welcome({ name: "Asha" });
await trivsend.emails.send({
  from: "Acme <noreply@notify.example.com>",
  to: "asha@example.com",
  subject: "Welcome to Acme",
  html: await render(email),
  // Mailbox providers like a plain-text part too.
  text: await render(email, { plainText: true }),
});

Framework quickstarts

Each takes about five minutes once your domain is verified and you have a key. Keep the key in an environment variable or secret store, never in code.

Next.js (App Router)

bash
npm install trivsend
# .env.local
TRIVSEND_API_KEY=ts_...
ts
// app/api/welcome/route.ts — runs on the server only, so the key never reaches the browser
import { TrivSend } from "trivsend";

const trivsend = new TrivSend(process.env.TRIVSEND_API_KEY);

export async function POST(req: Request) {
  const { email, name } = await req.json();
  const { data, error } = await trivsend.emails.send(
    {
      from: "Acme <noreply@notify.example.com>",
      to: email,
      subject: "Welcome to Acme",
      html: `<p>Hi ${name.replace(/[<>&]/g, "")}, your account is ready.</p>`,
      text: `Hi ${name}, your account is ready.`,
    },
    { idempotencyKey: `welcome-${email}` },
  );
  if (error) return Response.json({ error: error.message }, { status: 502 });
  return Response.json({ id: data!.id });
}

The same call works in a Server Action. For designed emails, render a React Email component to html first (React Email). On Vercel, add the variable under Settings → Environment Variables.

Node.js (Express, Fastify, NestJS)

Use the SDK as in Next.js, or plain fetch (Code examples). Send from a background job rather than inside the request when you can, and use an Idempotency-Key so a retried job doesn't send twice.

Python (Django)

Django's SMTP backend works as is. In settings.py:

python
import os

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.trivsend.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "trivsend"
EMAIL_HOST_PASSWORD = os.environ["TRIVSEND_API_KEY"]
DEFAULT_FROM_EMAIL = "Acme <noreply@notify.example.com>"
SERVER_EMAIL = DEFAULT_FROM_EMAIL

send_mail(), password-reset emails and admin error emails now go through TrivSend. For Flask, FastAPI or anything else, use the Python SDK:

bash
pip install trivsend
python
from trivsend import TrivSend, TrivSendError

client = TrivSend()  # reads TRIVSEND_API_KEY
try:
    email = client.emails.send({"from": "Acme <noreply@notify.example.com>", "to": "asha@example.com", "subject": "Hi", "text": "Hello"}, idempotency_key="welcome-42")
except TrivSendError as e:
    print(e.name, e.message)

It has no dependencies (Python 3.9+), uses the API's field names, raises TrivSendError for API errors, and has verify_webhook(raw_body, headers, secret) for webhooks. The resources are emails (with check), batch, domains, api_keys, templates (with gallery), contacts, suppressions, webhooks and validations.

PHP (Laravel)

Laravel's SMTP mailer works as is. In .env (Laravel 11 and later):

bash
MAIL_MAILER=smtp
MAIL_HOST=smtp.trivsend.com
MAIL_PORT=587
MAIL_USERNAME=trivsend
MAIL_PASSWORD=ts_...
MAIL_FROM_ADDRESS=noreply@notify.example.com
MAIL_FROM_NAME="${APP_NAME}"

Port 587 upgrades to TLS on its own. On Laravel 10 and earlier, also set MAIL_ENCRYPTION=tls. Run php artisan config:clear after changing .env, then send a test from php artisan tinker:

php
Mail::raw('It works', fn ($m) => $m->to('you@example.com')->subject('TrivSend test'));

Queued mailables (ShouldQueue) are recommended so a slow network never delays a page.

For the API from plain PHP (or Laravel, for things SMTP can't do: templates, expiry, checks), use the PHP SDK:

bash
composer require trivsend/trivsend
php
$trivsend = new \TrivSend\TrivSend(); // reads TRIVSEND_API_KEY
$email = $trivsend->emails->send(['from' => 'Acme <noreply@notify.example.com>', 'to' => 'asha@example.com', 'subject' => 'Hi', 'text' => 'Hello'], idempotencyKey: 'welcome-42');

PHP 8.1+, no dependencies. API errors throw TrivSend\TrivSendException (->name, ->statusCode). TrivSend\Webhook::verify($rawBody, getallheaders(), $secret) checks webhooks.

WordPress

WordPress sends through PHP's mail() by default, which most hosts don't deliver well.

With the TrivSend plugin:

  1. Install it (Plugins → Add New → Upload, with the plugin's zip from support@trivsend.com until it's listed on wordpress.org).
  2. Under Settings → TrivSend, paste a sending-access API key and set the From address.
  3. Send a test from the same page.

To keep the key out of the database, set it in wp-config.php instead: define('TRIVSEND_API_KEY', 'ts_...'); and define('TRIVSEND_FROM_EMAIL', 'wordpress@notify.example.com');.

Or with WP Mail SMTP, the free plugin many sites already have: choose Other SMTP and fill in:

SettingValue
SMTP Hostsmtp.trivsend.com
EncryptionTLS
SMTP Port587
Auto TLSOn
AuthenticationOn
SMTP Usernametrivsend
SMTP Passworda TrivSend API key with sending access
From Emailan address on your verified domain, with Force From Email on

To keep the key out of the database, define it in wp-config.php instead:

php
define( 'WPMS_ON', true );
define( 'WPMS_MAILER', 'smtp' );
define( 'WPMS_SMTP_HOST', 'smtp.trivsend.com' );
define( 'WPMS_SMTP_PORT', 587 );
define( 'WPMS_SSL', 'tls' );
define( 'WPMS_SMTP_AUTH', true );
define( 'WPMS_SMTP_AUTOTLS', true );
define( 'WPMS_SMTP_USER', 'trivsend' );
define( 'WPMS_SMTP_PASS', 'ts_...' );
define( 'WPMS_MAIL_FROM', 'noreply@notify.example.com' );
define( 'WPMS_MAIL_FROM_FORCE', true );

Then WP Mail SMTP → Tools → Email Test. WooCommerce order emails, contact forms and password resets all use the same settings.

Supabase Auth, Keycloak and other SMTP settings

Anything with an SMTP form uses the SMTP relay settings: host smtp.trivsend.com, port 587, username trivsend, a sending-access key as the password, and a sender on your verified domain. In Supabase: Authentication → Emails → SMTP Settings.

Marketing: contacts and broadcasts

For newsletters and announcements (full-access key):

How a broadcast did: GET /broadcasts/:id/stats returns delivered, bounced and pending counts; unique and total opens and clicks with rate (of delivered) and click_to_open_rate; spam complaints; a timeline of opens and clicks per hour for the first three days, then per day; the top_links clicked; and opens by devices (desktop, mobile, tablet, unknown) and mail clients. The broadcast's page in the dashboard shows the same. Gmail and Yahoo load images through their own servers, so their opens count as unknown devices, and Apple Mail can load images without the email being read, which raises open rates.

Importing and exporting contacts

POST /contacts/import adds up to 1,000 contacts per call. Send bigger lists in several calls; the dashboard's Contacts → Import CSV does that for you after you map the file's columns.

json
{
  "contacts": [
    { "email": "asha@example.com", "first_name": "Asha", "properties": { "city": "Pune" } },
    { "email": "ben@example.com", "unsubscribed": true }
  ],
  "segment_id": "seg_...",
  "update_existing": true,
  "start_automations": false
}

The answer counts what happened and lists rows it couldn't use (row numbers start at 1):

json
{ "object": "contact_import", "created": 1, "updated": 1, "skipped": 0, "added_to_segment": 2, "automations_started": 0, "errors": [] }

Existing contacts are updated unless update_existing is false. Fields you leave out keep their values, and properties merge with the ones already stored. Imports don't start automations unless start_automations is true, because an imported list is usually people who signed up long ago. The whole call is refused with 403 plan_limit_exceeded if it would take you over your plan's contact limit.

GET /contacts/export (or ?segment_id=) and GET /suppressions/export return CSV files. Text that starts with =, +, - or @ gets a leading ' so spreadsheets don't treat it as a formula.

A/B subject tests

Add ab_test to a broadcast to try two subject lines on part of the segment first:

json
{ "ab_test": { "subject_b": "Last day: 20% off", "sample_percent": 20, "wait_minutes": 240, "metric": "opens" } }

When you send, sample_percent of the segment (10 to 50) gets either subject or subject_b, half and half. After wait_minutes (15 to 2,880), the subject with the higher unique open rate (or click rate, with "metric": "clicks") goes to everyone else; a tie keeps subject. The segment needs at least 100 subscribed contacts. Until the winner goes out the broadcast is queued, and cancelling it stops the rest. GET /broadcasts/:id shows ab_test.winner once decided, and /stats has an ab_test section with each subject's delivered count and open and click rates. Send "ab_test": null to remove a test from a draft.

Automations

An automation sends a series of emails by itself, for example a welcome series or a follow-up when someone starts a trial:

json
POST /automations
{
  "name": "Welcome",
  "trigger": { "type": "contact_created" },
  "from": "Acme <hello@news.example.com>",
  "steps": [
    { "delay_minutes": 0, "subject": "Welcome to Acme", "html": "<p>Hi {{{FIRST_NAME|there}}}</p>" },
    { "delay_minutes": 2880, "subject": "Three tips to get started", "html": "..." }
  ]
}

Every broadcast gets one-click List-Unsubscribe headers and an unsubscribe link, unless your HTML places {{{UNSUBSCRIBE_URL}}} itself. Contact properties can be used as {{{key}}}. Keep marketing on a different sending subdomain (for example news.example.com) from your transactional mail.

Best practices

Endpoint reference

All paths are relative to https://api.trivsend.com.

Method and pathKeyPurpose
POST /emailssendingSend one email
POST /emails/batchsendingSend up to 100 emails
GET /emailsfullList and search sent email
POST /emails/checksendingPre-send check; nothing is sent
GET /emails/exportfullThe log as CSV, with the same filters
GET /emails/:idfullOne email and its last event
GET /emails/:id/eventsfullDelivery history with bounce and failure reasons
PATCH /emails/:idfullReschedule a scheduled email
POST /emails/:id/cancelfullCancel a scheduled email
GET /emails/receivingfullList received email
GET /emails/receiving/:idfullOne received email with its body
GET /emails/receiving/:id/attachments/:attachmentIdfullDownload an attachment (base64)
POST /validationssendingValidate one address
POST /validations/batchsendingValidate up to 100 addresses
GET /usageanyPlan, quotas and usage; status, paused_reason and paused_automatically (an owner can resume from the dashboard)
GET /plansanyPlans you can move to, with limits
GET /stats?start=&end=&stream=fullDaily counts and rates (dates YYYY-MM-DD, up to 92 days), and time to send
GET /deliverability?days=fullBounces and blocks by provider, reasons, sending IP and domain checks
POST /domains, GET /domainsfullAdd, list domains
GET, PATCH, DELETE /domains/:idfullInspect (with DNS records), change settings, remove
POST /domains/:id/verifyfullCheck DNS now
GET /domains/:id/dns-providerfullWhere the DNS is hosted, and each record's host there
POST /domains/:id/dns/cloudflarefullAdd the records at Cloudflare with a one-time API token, then verify
POST /domains/:id/dns/sharefullEmail the records to whoever manages the DNS
GET /domains/:id/dmarc-reportsfullDMARC aggregate reports received for the domain, with readiness for a stricter policy
POST /api-keys, GET /api-keysfullCreate (token shown once), list
PATCH, DELETE /api-keys/:idfullRename or set allowed_ips, revoke
GET /request-logsfullRequests made with your API keys; filter by api_key_id, status (success, error, 2xx, 4xx, 5xx), method
POST /templates, GET /templatesfullCreate, list templates
GET, PATCH, DELETE /templates/:idOrAliasfullRead, edit draft, delete
POST /templates/:idOrAlias/publish, /duplicatefullPublish (returns the version), copy
POST /templates/:idOrAlias/previewfullRender with test values
GET /templates/gallery, POST /templates/gallery/:idfullReady-made templates; add one, published
GET /templates/:idOrAlias/versions[/:version], POST …/versions/:version/restorefullPublished versions; copy one into the draft
POST /webhooks, GET /webhooksfullCreate, list webhooks
GET, PATCH, DELETE /webhooks/:idfullInspect, change (endpoint, events, status), remove
POST /webhooks/:id/signing-secret/rotatefullNew signing secret
GET /webhooks/:id/events[/:eventId]fullDelivery log
POST /webhooks/:id/events/:eventId/replayfullSend an event again
POST /webhooks/:id/events/replay-failedfullSend failed events of the last days again
POST /webhooks/:id/testfullSend a sample event now and see the answer
POST /suppressions, GET /suppressionsfullAdd, list
GET, DELETE /suppressions/:idOrEmailfullCheck, remove
POST /suppressions/batch/add, /batch/removefullUp to 100 at once
POST /contacts, GET /contactsfullCreate or update, list contacts
GET, PATCH, DELETE /contacts/:idOrEmailfullRead, change, delete
GET /contacts/:idOrEmail/segments, POST/DELETE .../segments/:segmentIdfullA contact's segments
GET, PATCH /contacts/:idOrEmail/topicsfullA contact's topic subscriptions
POST /segments, GET /segments, GET/PATCH/DELETE /segments/:id, GET /segments/:id/contactsfullSegments
POST /topics, GET /topics, GET/PATCH/DELETE /topics/:idfullTopics
POST /broadcasts, GET /broadcasts, GET/PATCH/DELETE /broadcasts/:idfullBroadcasts
POST /broadcasts/:id/send, /cancel, /duplicatefullSend (now or scheduled_at), cancel, copy
GET /broadcasts/:id/statsfullOpens, clicks, links and devices; A/B results
POST /contacts/import, GET /contacts/exportfullImport up to 1,000 contacts per call; CSV export
GET /suppressions/exportfullSuppression list as CSV
POST /automations, GET /automations, GET/PATCH/DELETE /automations/:idfullAutomations (drip series)
POST /automations/:id/activate, /pause, GET /automations/:id/statsfullTurn on or pause; contacts and per-step results
GET /healthnoneService health
GET /statusnoneComponent status and incidents (what status.trivsend.com shows)

MCP server for AI coding tools

TrivSend is also an MCP server, so Claude Code, Cursor, VS Code and other MCP clients can send email and set up domains for you. It is remote: nothing to install. Use a test key (ts_test_...) while trying it, or a sending-access key if the agent should only send.

ToolWhat it doesKey needed
send_emailSends an email (from, to, subject, html/text, cc, bcc, reply_to, tags, scheduled_at, attachments, idempotency_key)any
get_emailStatus and delivery events of an email, with bounce reasonsfull access
list_emailsRecent emails, by recipient or statusfull access
list_domains, get_domainSending domains and the DNS records to publishfull access
create_domain, verify_domainAdds a domain, then checks its DNSfull access
list_templatesHosted templatesfull access
get_deliverability_statsDelivery, bounce and complaint rates by mailbox provider, top bounce reasons, each domain's DKIM, SPF and DMARCfull access
validate_emailChecks one address before you send to it (counts toward the hourly validation limit)any

Claude and ChatGPT sign in instead of using a key: add https://api.trivsend.com/mcp as a custom connector and approve it on TrivSend's consent page. You pick the account and what the app may do (read, send, manage domains, validate). Sends are test sends unless an owner or admin ticks Allow live sending, and an app sends to one recipient at a time, 20 an hour. See and disconnect apps under Connected apps in the dashboard.

Other AI apps that let you add a custom MCP connector with OAuth sign-in (for example Gemini, Mistral Le Chat or Perplexity, where your plan allows custom connectors) work the same way: give them the URL and approve on the consent page.

Claude Code:

bash
claude mcp add --transport http trivsend https://api.trivsend.com/mcp --header "Authorization: Bearer $TRIVSEND_API_KEY"

Cursor (~/.cursor/mcp.json or .cursor/mcp.json):

json
{
  "mcpServers": {
    "trivsend": { "url": "https://api.trivsend.com/mcp", "headers": { "Authorization": "Bearer ${env:TRIVSEND_API_KEY}" } }
  }
}

VS Code (.vscode/mcp.json; it asks for the key once and stores it securely):

json
{
  "inputs": [{ "type": "promptString", "id": "trivsend-key", "description": "TrivSend API key", "password": true }],
  "servers": {
    "trivsend": { "type": "http", "url": "https://api.trivsend.com/mcp", "headers": { "Authorization": "Bearer ${input:trivsend-key}" } }
  }
}

Gemini CLI (~/.gemini/settings.json):

json
{
  "mcpServers": {
    "trivsend": { "httpUrl": "https://api.trivsend.com/mcp", "headers": { "Authorization": "Bearer $TRIVSEND_API_KEY" } }
  }
}

Any other client: Streamable HTTP at https://api.trivsend.com/mcp, Authorization: Bearer <key>. The server is stateless and answers in JSON. Errors from the API (unverified domain, plan limit, validation) come back as tool results marked isError, with the same name and message as the REST API.

TrivSend is listed in the official MCP Registry as com.trivsend/mcp, so clients and directories that read the registry can find it by name.

Single sign-on for your team

On the Pro plan, owners can let their team sign in to the dashboard through the company's identity provider (any OpenID Connect provider). Under Settings → Single sign-on:

  1. At your provider, create an OpenID Connect web application with the redirect URI shown there (https://app.trivsend.com/auth/sso/callback) and the scopes openid email profile.
  2. Enter its issuer URL, client ID and client secret, and the email domains your staff use. Each domain must be one of your verified sending domains or its parent (notify.example.com lets you use example.com).
  3. Choose the role for people signing in for the first time. Then sign in from Log in → Sign in with SSO in a private window to check it.
  4. Optionally require single sign-on: password and Google sign-in are then refused for those domains.
ProviderIssuer URL
Microsoft Entra IDhttps://login.microsoftonline.com/<tenant-id>/v2.0
Oktahttps://<your-org>.okta.com (or .../oauth2/default)
Google Workspacehttps://accounts.google.com
Auth0, Keycloak, othersthe issuer from their /.well-known/openid-configuration

API keys are separate from sign-in: revoke a leaver's keys under API keys.

Instructions for AI coding assistants

If you are an AI assistant adding TrivSend to a codebase, follow these rules:

  1. Read the key from an environment variable (TRIVSEND_API_KEY). Never hard-code it, never log it, never send it to a browser.
  2. Call POST https://api.trivsend.com/emails from server-side code only, with Authorization: Bearer <key> and Content-Type: application/json.
  3. Put the from address on a domain the user has verified in TrivSend. If you don't know it, read it from configuration (for example TRIVSEND_FROM) and ask the user for the value.
  4. Send both html and text.
  5. Set an Idempotency-Key derived from the business event (for example password-reset-<token id>), and reuse it on retries.
  6. Treat 200 with an id as "queued", not "delivered". Store the id if the app needs to track delivery.
  7. On errors, read name from the JSON body. Retry only network errors, 429 rate_limit_exceeded and 5xx, with backoff.
  8. For delivery outcomes, add a webhook endpoint that verifies the signature over the raw body (see Verify the signature) and returns 2xx quickly.
  9. In tests, use a ts_test_ key or delivered@simulator.trivsend.com; never send real email from CI.
  10. Don't invent endpoints or fields. Everything TrivSend supports is in this guide.
  11. If your client supports MCP, the user can connect you to https://api.trivsend.com/mcp (MCP server) to send test emails and check domains directly.

Support

json
{
  "object": "status",
  "status": "operational",
  "components": [{ "id": "sending", "name": "Email sending", "status": "operational" }],
  "incidents": [],
  "past_incidents": []
}

status is operational, degraded, partial_outage or major_outage. Components: api, sending, marketing, webhooks, dashboard, inbound. Incidents are posted automatically within minutes of a measured problem ("automatic": true), and our team adds detail when there's more to say. After a major incident of 15 minutes or more, account owners who sent email during it get a short summary by email.