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.
- API base URL:
https://api.trivsend.com - Dashboard:
https://app.trivsend.com - SMTP relay:
smtp.trivsend.com, port 587 (STARTTLS) or 465 (TLS) - This guide as plain Markdown:
https://trivsend.com/docs.md(point an AI assistant at it)
Quick start
Four steps from zero to a delivered email.
- Create an account at
https://app.trivsend.com/signupand 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. - 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. - 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 exampleTRIVSEND_API_KEY. - Send:
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"
}'{ "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:
Authorization: Bearer ts_xxxxxxxxxxxxxxxxxxxxxxxx| Key type | Prefix | Can do |
|---|---|---|
| Full access | ts_ | Everything in this guide |
| Sending access | ts_ | POST /emails, POST /emails/batch, POST /validations, GET /usage. Can be limited to one domain with domain_id |
| Test | ts_test_ | Sending access, but nothing is delivered: every email is accepted, logged and simulated. See Testing |
Rules for keys:
- Keep keys on the server. Never put one in browser or mobile app code.
- Give each app and environment its own key, so you can revoke one without touching the others.
- Use a sending-access key unless the app really manages domains, webhooks or contacts.
- Lock a key to your servers' addresses with
allowed_ips(addresses or CIDR ranges, IPv4 or IPv6), onPOST /api-keysor later withPATCH /api-keys/:id, or under API keys in the dashboard. From anywhere else the key is refused withinvalid_api_key, over the API and the SMTP relay alike. An empty list allows any address.
{ "name": "production", "permission": "sending_access", "allowed_ips": ["203.0.113.10", "10.20.0.0/16"] }Sending email
POST /emails
Send one email.
| Field | Type | Required | Notes |
|---|---|---|---|
from | string | yes* | "Name <addr@domain>" or "addr@domain". The domain must be verified in your account |
to | string or string[] | yes | Up to 50 recipients across to, cc and bcc |
cc, bcc | string or string[] | no | |
reply_to | string or string[] | no | |
subject | string | yes* | Up to 998 characters |
html | string | one of* | HTML body |
text | string | one of* | Plain-text body. Send both for the best inbox placement |
headers | object | no | Extra headers, e.g. {"X-Entity-Ref-ID": "123"}. From, To, Subject, Message-ID, Date and similar are set by TrivSend |
tags | {name, value}[] | no | Up to 50. Letters, numbers, _ and - only. Searchable and included in webhooks |
attachments | object[] | no | Up to 20. See Attachments |
scheduled_at | string | no | Send later. See Scheduling |
template | {id, variables} | no | Send a hosted template instead of html/text. See Templates |
priority | "high", "normal" or "low" | no | TrivSend extension. Order in the delivery queue; see Priority. Default normal |
expires_at | string | no | TrivSend 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:
{ "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.
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"}
]'{ "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:
{ "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" }expires_atmust be at least 10 seconds from now, afterscheduled_atif you set one, and at most 24 hours after the email is due.- An email with
expires_atgoes out athighpriority unless you setpriority. - If it hasn't been handed to TrivSend's mail server by then (a long queue, retries after a temporary error, a paused account), it ends
failed. You get theemail.failedwebhook withfailed.expired: trueandfailed.expires_at, usually within a minute of the expiry. Use it to send the code another way, by SMS or WhatsApp:
// In your webhook handler
if (event.type === "email.failed" && event.data.failed.expired) {
await sendSms(event.data.to[0], "Your code is ...");
}- Expiry covers the time until our mail server accepts the email (
sent). After that, the receiving server delivers it, and an email can't be recalled. - If your library drops fields it doesn't know, or you send through the SMTP relay, use the header
X-TrivSend-Expires-Atwith an ISO time or a number of seconds from now (X-TrivSend-Expires-At: 300). TrivSend removes it before sending.
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:
- Setup: a domain that isn't verified or has missing DNS records, recipients on your suppression list, no DMARC.
- Subject: all capitals, or spam-like words and punctuation.
- Body: no plain-text part, mostly images,
<script>or<form>, HTML over Gmail's 102 KB clipping limit. - Links: URL shorteners, many other domains, no unsubscribe on promotional mail.
- Size: attachments over 10 MB.
{
"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):
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):
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:
$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):
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
"attachments": [
{
"filename": "invoice-1042.pdf",
"content": "JVBERi0xLjQKJ...",
"content_type": "application/pdf"
},
{
"filename": "logo.png",
"content": "iVBORw0KGgo...",
"content_id": "logo"
}
]contentis the file encoded as base64. Or givepath, anhttps://(orhttp://) URL: TrivSend downloads it when it accepts the email, so a link that fails returns422 validation_errornaming the attachment, and a file changed later doesn't change the email. Up to 20 URLs per request and 10 MB downloaded per email; private and internal addresses are refused;content_typedefaults to the server's.
"attachments": [{ "filename": "invoice-1042.pdf", "path": "https://files.example.com/invoices/1042.pdf" }]content_idmakes an inline image: reference it in the HTML as<img src="cid:logo">.- The whole request may be up to 15 MB, so keep attachments under about 10 MB in total (base64 adds a third).
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:
- an ISO 8601 timestamp with a timezone:
"2026-11-01T09:00:00+05:30"or"2026-11-01T03:30:00Z"; - or a phrase:
"in 10 minutes","in 2 hours","in 3 days".
A scheduled email has status scheduled until it goes out. Change or cancel it:
# 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):
{
"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"
}status | Meaning |
|---|---|
scheduled | Waiting for scheduled_at |
queued, sending | Accepted, being delivered |
sent | The recipient's mail server accepted it |
bounced | The recipient's server rejected it (after it was sent) |
failed | Could not be delivered after all retries, or expired before it could be sent (expires_at) |
suppressed | Not sent: every recipient is on your suppression list |
canceled | A 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.
{
"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.
"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).
List and search
GET /emails (full access) returns the newest first and takes these filters, which combine:
| Query | Example |
|---|---|
recipient | user@example.com (matches to, cc and bcc) |
status | sent,bounced |
tag | category=otp |
subject, from | partial, case-insensitive |
stream | transactional or marketing |
test | true or false |
created_after, created_before | 2026-10-01T00:00:00Z |
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:
limit: 1 to 100, default 20;after=<id>: the next page (older items), using the lastidyou received;before=<id>: the previous page.
{ "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:
{ "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.
| Status | name | What to do |
|---|---|---|
| 401 | missing_api_key | Send the Authorization: Bearer header |
| 403 | invalid_api_key | The key is wrong or revoked |
| 401 | restricted_api_key | A sending-access key called a full-access endpoint, or used another domain |
| 403 | invalid_from_address | Add and verify the from domain |
| 403 | account_pending_review | Your 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 |
| 403 | tenant_paused, tenant_suspended | Sending 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 |
| 404 | not_found | Wrong id, or it belongs to another account |
| 422 | validation_error | The message names the field and the problem |
| 429 | rate_limit_exceeded | Too many requests per second; retry after a short pause |
| 429 | daily_quota_exceeded, monthly_quota_exceeded | Plan limit reached; resets at midnight UTC or on the 1st |
| 500 | application_error | Retry 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:
curl -H "Authorization: Bearer $KEY" https://api.trivsend.com/usage{
"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.
{
"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:
"features": { "log_days": 30, "max_members": null, "content_retention_control": false, "max_client_accounts": 0, "signed_dpa": false, "support_reply_hours": 24 }| Free | Starter | Growth | Pro | |
|---|---|---|---|---|
Email log kept (log_days) | 7 days | 30 days | 90 days | 90 days |
| People on the account | 1 | any | any | any |
| Choose content retention | no | no | yes | yes |
| Client accounts | 0 | 0 | 5 | 25 |
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.
- The agency's owners become owners of the client account; switch to it with the account menu in the dashboard.
- It starts on the Free plan. Upgrade it like any account; invoices go to the agency, whose billing details are copied in.
- The same page lists them with this month's sent, bounced and complained counts.
- A client account can't have client accounts of its own.
Weekly report
Every Monday morning (India time), the owners and admins of an account that sent mail that week get one email:
- emails sent, compared with the week before;
- bounce and complaint rates;
- how fast transactional mail went out;
- the most common bounce reason, with what to do;
- any domain with missing DNS records.
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:
0deletes the content as soon as an email is sent (or fails), so one-time codes don't stay in our database.- Content is deleted within the hour after the period; emails still queued or scheduled keep theirs until they're sent.
- Leaving it empty goes back to the default; you can't choose longer than the default.
- Delivery events, the email log and your suppression list keep their normal periods.
GET /accountshowscontent_retention_daysandcontent_retention_custom.
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.
issues: what to fix, worst first (severityisproblemorwarning).providers: sent, bounced, blocked, hard and soft bounces and complaints per mailbox provider (gmail,yahoo,microsoft,apple,zoho,other). Company domains count under the provider their MX points to, so Google Workspace isgmail.blockedmeans rejected by policy (5.7.x), which is about the sender, not the address, so those addresses aren't suppressed.top_reasons: what receivers said, grouped across messages, with ahintfor common causes.sending_ips: live checks of TrivSend's sending IPs: reverse DNS (Gmail and Yahoo reject mail without it), and blocklists (listedisnullwhen a list didn't answer).domains: DKIM, SPF, return path and DMARC for each of your domains, with 30 days of DMARC report totals andreadiness.
Numbers cover emails created in the window, with the bounces and complaints they got afterwards; test mode and simulator addresses are left out.
{
"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.
"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:
| Record | Type | Name | Value |
|---|---|---|---|
| DKIM | TXT | trivsend._domainkey.notify.example.com | v=DKIM1; k=rsa; p=... (unique per domain) |
| Return path | MX | bounces.notify.example.com | mail.trivsend.com, priority 10 |
| SPF | TXT | bounces.notify.example.com | v=spf1 include:_spf.trivsend.com ~all |
| DMARC (recommended) | TXT | _dmarc.notify.example.com | v=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:
- SPF is checked on the
bounces.return-path subdomain, so your domain's existing SPF record does not change. - With Cloudflare, records must be DNS only (grey cloud). TXT and MX records always are.
- DNS watch. TrivSend checks every verified domain's records again every 6 hours. If a record that was there goes missing (a DNS clean-up, a move to another DNS provider), and it's still missing 30 minutes later, the account's owners and admins get an email naming the record, where it goes and what breaks without it. They get another email when it's back. Sending isn't stopped.
GET /domains/:idshowsdns_watch: { checked_at, missing, since }(missingis empty when all is well), and the domain page shows a warning. - Start DMARC at
p=noneand tighten top=quarantine, thenp=reject, once the reports look clean (see DMARC reports). If your domain already has a DMARC record, addmailto:dmarc@feedback.trivsend.comto itsrua(comma-separated, next to any address you already use).
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.
- Cloudflare: one click.
- In Cloudflare, create an API token with the Edit zone DNS template, limited to the domain's zone.
- Paste it on the domain page.
- TrivSend adds the records (DNS only), then verifies the domain.
The token is used for that one request and never stored. TrivSend only adds records:
- an existing SPF record at the same name gets TrivSend's
include:added; - an existing DMARC policy is kept;
- anything else in the way is reported to you and left unchanged.
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.
- Connect automatically (Domain Connect). Where your DNS provider supports Domain Connect and has accepted TrivSend's template, the domain page shows Connect. You sign in at your provider, see exactly which records TrivSend asks for, approve them, and come back to a verified domain. No token is shared.
GET /domains/:id/dns-providerreturns the signed link indomain_connect.apply_url(otherwisenull). - Other providers (GoDaddy, Hostinger, Namecheap, Route 53 and more): step-by-step instructions for that provider. Each record shows the host to type there (for example
bounces.notifywhen the zone isexample.com).GET /domains/:id/dns-providerreturns the provider, the zone and each record'shost. - Someone else manages your DNS? Use Email the records on the domain page, or
POST /domains/:id/dns/share {"email": "it@example.com"}. It sends them the records with instructions for their provider. Limited to 10 a day per account.
All three need a full-access key.
Domain settings, with PATCH /domains/:id:
| Field | Effect |
|---|---|
open_tracking, click_tracking | true/false. Off by default |
tracking_subdomain | e.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 |
inbound | true 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:
- Where: each report shows on the domain's page in the dashboard and in
GET /domains/:id/dmarc-reports, which is paginated and returns the newest first. - What: messages, how many passed DMARC, and the IPs that failed.
- Alerts: owners and admins of your account get one email a day summarising the reports with failures, with the failing sources and what to do (clean reports arrive silently), and an email if no report has arrived for 3 days, which usually means the
ruaaddress was removed from the DMARC record. - When to tighten: the list response includes
readiness, which says whether the reports support the next policy: at least 14 days of reports, 98% passing and none of TrivSend's own mail failing.
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.
{
"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": [ … ]
}{
"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:
{
"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:
{
"to": "user@example.com",
"template": { "id": "otp", "variables": { "CODE": "482913", "NAME": "Asha" } }
}- Placeholders are
{{{NAME}}}, or{{{NAME|fallback}}}with a default. - Values are HTML-escaped in the HTML body, so user input can't inject markup.
- Sends always use the published version; edits are drafts until you publish again.
from,subjectandreply_toin the request override the template's.
Ready-made templates
TrivSend has a library of ready-made transactional templates:
- sign-in code (OTP), in English and Hindi;
- password reset, in English and Hindi;
- magic sign-in link;
- welcome;
- payment receipt;
- confirm a new email address.
Each has a plain-text part, works on phones and in dark mode, and is far under Gmail's clipping size.
# 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:
{ "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:
{ "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:
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"]}'{ "object": "webhook", "id": "...", "signing_secret": "whsec_..." }Store signing_secret; it is shown once (rotate it with POST /webhooks/:id/signing-secret/rotate).
Events
| Event | When |
|---|---|
email.scheduled | An email was scheduled |
email.sent | The recipient's server accepted it |
email.delivery_delayed | A temporary failure; TrivSend keeps retrying |
email.bounced | The address doesn't exist or rejected it; the address is now suppressed |
email.complained | The recipient marked it as spam; the address is now suppressed |
email.failed | Gave up after all retries, or expires_at passed first (failed.expired: true) |
email.suppressed | Not sent because the recipient is suppressed |
email.opened, email.clicked | With open/click tracking on |
email.received | Inbound mail arrived. See Receiving email |
contact.created, contact.updated, contact.deleted, contact.topics.updated | Marketing contacts changed |
domain.created, domain.updated, domain.deleted | Domains changed |
suppression.added, suppression.removed | The suppression list changed |
topic.created, topic.updated, topic.deleted | Topics changed |
Payload:
{
"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:
- Take the raw request body, exactly as received, before any JSON parsing.
- Compute HMAC-SHA256 over
<webhook-id>.<webhook-timestamp>.<raw body>, keyed with the base64-decoded part of the secret afterwhsec_. - Base64 the result and compare it with each
v1,<signature>entry inwebhook-signature(space-separated), in constant time. - Reject timestamps more than 5 minutes from now, to stop replays.
Node.js (Express):
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):
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 "", 200Delivery and retries
- Reply with any
2xxwithin 15 seconds. Do slow work after replying, or in a queue. - Failed deliveries are retried after 5 seconds, 5 minutes, 30 minutes, 2, 5, 10 and 10 hours, then dropped.
- The same event keeps the same
webhook-idacross retries and replays; use it to ignore duplicates. - Events can arrive out of order. Use
created_atwhen order matters. - Each delivery is logged:
GET /webhooks/:id/events, andPOST /webhooks/:id/events/:eventId/replaysends one again. GET /webhooks/:id/events/:eventIdincludeshistory: every attempt with theresponse_status, the first 1,000 characters ofresponse_body, theerrorandduration_ms. The dashboard shows it when you click an event.POST /webhooks/:id/events/replay-failed(optional body{"days": 7}, 1 to 30) sends every failed event of that period again, at most 1,000. The response says how many:{"replayed": 12}.
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.
{ "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:
| Type | Name | Value |
|---|---|---|
| MX | inbound.notify.example.com | mail.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:
curl -H "Authorization: Bearer $KEY" https://api.trivsend.com/emails/receiving/$EMAIL_ID{
"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:
curl -X POST https://api.trivsend.com/validations \
-H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
-d '{"email": "asha@gmial.com"}'{
"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 }
}result | reason | Suggested handling |
|---|---|---|
valid | accepted | Accept. If did_you_mean is set, ask "Did you mean ...?" |
risky | disposable, role_address | Accept or warn, your choice |
invalid | invalid_syntax, no_mail_server, suppressed | Reject or ask for another address |
unknown | dns_error | Accept; 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.
| Request | Purpose |
|---|---|
GET /suppressions?origin=bounce | List (origins: bounce, complaint, unsubscribe, manual) |
POST /suppressions {"email": "..."} | Block an address yourself |
GET /suppressions/:idOrEmail | Is this address suppressed, and why |
DELETE /suppressions/:idOrEmail | Remove one, for example after a user fixed their mailbox |
POST /suppressions/batch/add, /batch/remove | Up 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 to | Result |
|---|---|
delivered@simulator.trivsend.com | sent |
bounced@simulator.trivsend.com | sent, then a hard bounce and an email.bounced webhook |
complained@simulator.trivsend.com | sent, 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, ...):
| Setting | Value |
|---|---|
| Host | smtp.trivsend.com |
| Port | 587 with STARTTLS, or 465 with TLS |
| Username | trivsend |
| Password | a 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.
npm install trivsend
TRIVSEND_API_KEY=ts_...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:
npm install trivsend @react-email/components react react-dom// 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>
);
}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)
npm install trivsend
# .env.local
TRIVSEND_API_KEY=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:
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_EMAILsend_mail(), password-reset emails and admin error emails now go through TrivSend. For Flask, FastAPI or anything else, use the Python SDK:
pip install trivsendfrom 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):
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:
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:
composer require trivsend/trivsend$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:
- Install it (Plugins → Add New → Upload, with the plugin's zip from support@trivsend.com until it's listed on wordpress.org).
- Under Settings → TrivSend, paste a sending-access API key and set the From address.
- 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:
| Setting | Value |
|---|---|
| SMTP Host | smtp.trivsend.com |
| Encryption | TLS |
| SMTP Port | 587 |
| Auto TLS | On |
| Authentication | On |
| SMTP Username | trivsend |
| SMTP Password | a TrivSend API key with sending access |
| From Email | an 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:
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):
- Contacts:
POST /contacts {"email", "first_name", "last_name", "properties": {...}}creates or updates by email.GET/PATCH/DELETE /contacts/:idOrEmail. - Segments: groups of contacts.
POST /segments {"name"}, thenPOST /contacts/:idOrEmail/segments/:segmentId. - Topics: what people can subscribe to, opt-in or opt-out by default.
PATCH /contacts/:idOrEmail/topicsupdates a contact's choices. - Broadcasts:
POST /broadcasts {"segment_id", "topic_id", "from", "subject", "html"}, thenPOST /broadcasts/:id/send(optionally withscheduled_at).
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.
{
"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):
{ "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:
{ "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:
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": "..." }
]
}triggeris{"type": "contact_created"}or{"type": "segment_joined", "segment_id": "..."}.- Each step waits
delay_minutesafter the previous one (the first after the trigger). Up to 10 steps. - Automations start as
draft.POST /automations/:id/activateturns one on, for contacts that match from then on.POST /automations/:id/pauseholds everyone at their next step. - A contact goes through an automation once. It stops early if they unsubscribe, are suppressed or deleted, leave the trigger segment, or opt out of the automation's
topic_id. - Steps count against your quota. They are marketing email, with an unsubscribe link and the tag
automation=<id>. GET /automations/:id/statsshows contacts in progress, finished and stopped, and per step how many were sent, opened and clicked.
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
- Send from a subdomain (
notify.,mail.) and keep transactional and marketing on different ones. - Always send
textwithhtml. Spam filters score HTML-only mail worse. - Use an
Idempotency-Keyon anything a retry could duplicate: OTPs, receipts, invoices. - Handle
email.bouncedandemail.complained: mark the address in your own database and stop asking the user to use it. - Don't send to addresses you didn't collect yourself, and honour unsubscribes. Complaint rates above 0.3% get mail blocked at Gmail and Outlook.
- Keep keys in secrets, one per app and environment, with sending access where possible.
- Watch
GET /usageand the Stats page for bounce and complaint rates.
Endpoint reference
All paths are relative to https://api.trivsend.com.
| Method and path | Key | Purpose |
|---|---|---|
POST /emails | sending | Send one email |
POST /emails/batch | sending | Send up to 100 emails |
GET /emails | full | List and search sent email |
POST /emails/check | sending | Pre-send check; nothing is sent |
GET /emails/export | full | The log as CSV, with the same filters |
GET /emails/:id | full | One email and its last event |
GET /emails/:id/events | full | Delivery history with bounce and failure reasons |
PATCH /emails/:id | full | Reschedule a scheduled email |
POST /emails/:id/cancel | full | Cancel a scheduled email |
GET /emails/receiving | full | List received email |
GET /emails/receiving/:id | full | One received email with its body |
GET /emails/receiving/:id/attachments/:attachmentId | full | Download an attachment (base64) |
POST /validations | sending | Validate one address |
POST /validations/batch | sending | Validate up to 100 addresses |
GET /usage | any | Plan, quotas and usage; status, paused_reason and paused_automatically (an owner can resume from the dashboard) |
GET /plans | any | Plans you can move to, with limits |
GET /stats?start=&end=&stream= | full | Daily counts and rates (dates YYYY-MM-DD, up to 92 days), and time to send |
GET /deliverability?days= | full | Bounces and blocks by provider, reasons, sending IP and domain checks |
POST /domains, GET /domains | full | Add, list domains |
GET, PATCH, DELETE /domains/:id | full | Inspect (with DNS records), change settings, remove |
POST /domains/:id/verify | full | Check DNS now |
GET /domains/:id/dns-provider | full | Where the DNS is hosted, and each record's host there |
POST /domains/:id/dns/cloudflare | full | Add the records at Cloudflare with a one-time API token, then verify |
POST /domains/:id/dns/share | full | Email the records to whoever manages the DNS |
GET /domains/:id/dmarc-reports | full | DMARC aggregate reports received for the domain, with readiness for a stricter policy |
POST /api-keys, GET /api-keys | full | Create (token shown once), list |
PATCH, DELETE /api-keys/:id | full | Rename or set allowed_ips, revoke |
GET /request-logs | full | Requests made with your API keys; filter by api_key_id, status (success, error, 2xx, 4xx, 5xx), method |
POST /templates, GET /templates | full | Create, list templates |
GET, PATCH, DELETE /templates/:idOrAlias | full | Read, edit draft, delete |
POST /templates/:idOrAlias/publish, /duplicate | full | Publish (returns the version), copy |
POST /templates/:idOrAlias/preview | full | Render with test values |
GET /templates/gallery, POST /templates/gallery/:id | full | Ready-made templates; add one, published |
GET /templates/:idOrAlias/versions[/:version], POST …/versions/:version/restore | full | Published versions; copy one into the draft |
POST /webhooks, GET /webhooks | full | Create, list webhooks |
GET, PATCH, DELETE /webhooks/:id | full | Inspect, change (endpoint, events, status), remove |
POST /webhooks/:id/signing-secret/rotate | full | New signing secret |
GET /webhooks/:id/events[/:eventId] | full | Delivery log |
POST /webhooks/:id/events/:eventId/replay | full | Send an event again |
POST /webhooks/:id/events/replay-failed | full | Send failed events of the last days again |
POST /webhooks/:id/test | full | Send a sample event now and see the answer |
POST /suppressions, GET /suppressions | full | Add, list |
GET, DELETE /suppressions/:idOrEmail | full | Check, remove |
POST /suppressions/batch/add, /batch/remove | full | Up to 100 at once |
POST /contacts, GET /contacts | full | Create or update, list contacts |
GET, PATCH, DELETE /contacts/:idOrEmail | full | Read, change, delete |
GET /contacts/:idOrEmail/segments, POST/DELETE .../segments/:segmentId | full | A contact's segments |
GET, PATCH /contacts/:idOrEmail/topics | full | A contact's topic subscriptions |
POST /segments, GET /segments, GET/PATCH/DELETE /segments/:id, GET /segments/:id/contacts | full | Segments |
POST /topics, GET /topics, GET/PATCH/DELETE /topics/:id | full | Topics |
POST /broadcasts, GET /broadcasts, GET/PATCH/DELETE /broadcasts/:id | full | Broadcasts |
POST /broadcasts/:id/send, /cancel, /duplicate | full | Send (now or scheduled_at), cancel, copy |
GET /broadcasts/:id/stats | full | Opens, clicks, links and devices; A/B results |
POST /contacts/import, GET /contacts/export | full | Import up to 1,000 contacts per call; CSV export |
GET /suppressions/export | full | Suppression list as CSV |
POST /automations, GET /automations, GET/PATCH/DELETE /automations/:id | full | Automations (drip series) |
POST /automations/:id/activate, /pause, GET /automations/:id/stats | full | Turn on or pause; contacts and per-step results |
GET /health | none | Service health |
GET /status | none | Component 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.
| Tool | What it does | Key needed |
|---|---|---|
send_email | Sends an email (from, to, subject, html/text, cc, bcc, reply_to, tags, scheduled_at, attachments, idempotency_key) | any |
get_email | Status and delivery events of an email, with bounce reasons | full access |
list_emails | Recent emails, by recipient or status | full access |
list_domains, get_domain | Sending domains and the DNS records to publish | full access |
create_domain, verify_domain | Adds a domain, then checks its DNS | full access |
list_templates | Hosted templates | full access |
get_deliverability_stats | Delivery, bounce and complaint rates by mailbox provider, top bounce reasons, each domain's DKIM, SPF and DMARC | full access |
validate_email | Checks 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:
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):
{
"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):
{
"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):
{
"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:
- At your provider, create an OpenID Connect web application with the redirect URI shown there (
https://app.trivsend.com/auth/sso/callback) and the scopesopenid email profile. - 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.comlets you useexample.com). - 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.
- Optionally require single sign-on: password and Google sign-in are then refused for those domains.
| Provider | Issuer URL |
|---|---|
| Microsoft Entra ID | https://login.microsoftonline.com/<tenant-id>/v2.0 |
| Okta | https://<your-org>.okta.com (or .../oauth2/default) |
| Google Workspace | https://accounts.google.com |
| Auth0, Keycloak, others | the 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:
- Read the key from an environment variable (
TRIVSEND_API_KEY). Never hard-code it, never log it, never send it to a browser. - Call
POST https://api.trivsend.com/emailsfrom server-side code only, withAuthorization: Bearer <key>andContent-Type: application/json. - Put the
fromaddress on a domain the user has verified in TrivSend. If you don't know it, read it from configuration (for exampleTRIVSEND_FROM) and ask the user for the value. - Send both
htmlandtext. - Set an
Idempotency-Keyderived from the business event (for examplepassword-reset-<token id>), and reuse it on retries. - Treat
200with anidas "queued", not "delivered". Store theidif the app needs to track delivery. - On errors, read
namefrom the JSON body. Retry only network errors,429 rate_limit_exceededand5xx, with backoff. - For delivery outcomes, add a webhook endpoint that verifies the signature over the raw body (see Verify the signature) and returns
2xxquickly. - In tests, use a
ts_test_key ordelivered@simulator.trivsend.com; never send real email from CI. - Don't invent endpoints or fields. Everything TrivSend supports is in this guide.
- 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
- Dashboard:
https://app.trivsend.com - Email:
support@trivsend.com(Monday to Saturday, 10:00 to 19:00 IST) - Policies: Terms, Privacy, Refunds, Acceptable use, Contact and Grievance Officer
- Service status:
https://status.trivsend.com, orGET https://api.trivsend.com/status(no key) for the same as 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.