Resend Integration Guide
Technology: resend · Category: comms · Last reviewed: 2026-10-20
Source: https://tech-stack.codeamanilabs.org/guide/resend
Insight:
Resend is codeAmani's email API: transactional sends with React Email templates, plus broadcasts, inbound mail, and webhooks. Send from a verified domain whose SPF/MX sit on the
send.subdomain, use idempotency keys, and handle bounce and complaint webhooks to stay under Gmail/Yahoo/Microsoft bulk-sender limits. For Kenya-targeted products, email backs up SMS and WhatsApp. It is never the primary channel there.
██████╗ ███████╗███████╗███████╗███╗ ██╗██████╗
██╔══██╗██╔════╝██╔════╝██╔════╝████╗ ██║██╔══██╗
██████╔╝█████╗ ███████╗█████╗ ██╔██╗ ██║██║ ██║
██╔══██╗██╔══╝ ╚════██║██╔══╝ ██║╚██╗██║██║ ██║
██║ ██║███████╗███████║███████╗██║ ╚████║██████╔╝
╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝╚═╝ ╚═══╝╚═════╝
Resend Integration Guide
Focus: Email for codeAmani products. Send transactional email with React Email templates, receive inbound mail, run opt-in marketing broadcasts, and track delivery through signed webhooks.
Overview
Resend is a developer-first email API from the team behind React Email. codeAmani uses it for auth notifications, payment receipts, onboarding flows, and system alerts. It now covers four jobs:
| Job | Resend feature | Billing |
|---|---|---|
| Transactional email (receipts, resets, alerts) | emails.send, batch.send, Templates |
By emails sent and received per month |
| Inbound email (support inbox, reply handling) | Receiving: email.received webhook + emails.receiving.get |
Counts toward the same email quota |
| Marketing email (newsletters, product news) | Contacts, Segments, Topics, Broadcasts | By contact count (separate Marketing plan) |
| Lifecycle flows (drip, trial expiry) | Automations triggered by events.send |
10,000 runs/month included |
Here is the core flow. Your app hands off to Resend, and delivery events come back to you over signed webhooks:
flowchart LR
A["Your App"] -->|"react: Template(props)"| C["resend.emails.send"]
C --> D["Resend API"]
D --> E["Recipient inbox"]
D -->|"Svix-signed events"| F["/api/webhooks/resend"]
F -->|"delivered / bounced / complained / received"| G["Update DB"]
Current versions (verified 2026-10-20)
| Package | Version | Notes |
|---|---|---|
resend (Node SDK) |
6.34.1 | Major v6. Depends on standardwebhooks and postal-mime. Optional peer: @react-email/render |
react-email |
6.11.3 | Components, render, pretty, and the email CLI all come from this one package |
@react-email/ui |
6.11.3 | Dev-only preview UI for email dev |
resend-mcp |
2.27.1 | Open-source MCP server. The hosted one is at https://mcp.resend.com/mcp |
resend-cli |
2.26.0 | Official CLI (resend binary), launched March 2026 |
svix |
2.8.0 | Optional. Only needed for manual webhook verification |
Deprecated, so don't use it:
@react-email/componentsis marked deprecated on npm. Import components fromreact-emailinstead.@react-email/renderis still published (2.1.1), but now it's an internal dependency ofreact-emailand the Resend SDK. You don't import it yourself.
What changed since the last review (2026-08-23)
- Audiences are now Segments. Since November 2025, contacts are global (one per email address), "Audiences" became Segments, and Topics handle unsubscribe preferences.
resend.audiencesis still there, but it's marked@deprecated. Useresend.segments. - Rate limit raised to 10 requests/second per team. The limit is shared across all API keys, with no burst allowance. Use
batch.sendto fit up to 100 emails in one request. - Received mail counts toward your quota. Each inbound email counts as one email, the same as a send.
- New API surface: Templates (
template: { id, variables }on send), Suppressions API, Events + Automations, Account Usage API (resend.usage.get()), Email Metrics API (resend.emails.metrics()), Logs API, Cancel/Duplicate Broadcast, Share Email, headless Webhooks API (resend.webhooks.create/list/rotateSigningSecret), and OAuth 2.1 for third-party apps. - Batch validation modes: pass
batchValidation: 'permissive'to send the valid emails and get per-index errors back. The default is'strict'. - Remote MCP server + official plugins for Claude, Claude Code, Cursor, and Codex. Inboxes (agent mailboxes) are in private beta.
Official Documentation
| Resource | URL |
|---|---|
| Resend Docs | https://resend.com/docs |
| API Reference | https://resend.com/docs/api-reference/introduction |
| Node.js SDK | https://github.com/resend/resend-node |
| React Email | https://react.email/docs |
| Webhooks | https://resend.com/docs/webhooks/introduction |
| Usage limits | https://resend.com/docs/api-reference/rate-limit |
| MCP server | https://resend.com/docs/mcp-server |
| Changelog | https://resend.com/changelog |
SDK Setup
npm install resend@6.34.1
import { Resend } from "resend";
// Server-side only. RESEND_API_KEY must never reach a client bundle.
const resend = new Resend(process.env.RESEND_API_KEY);
First-party SDKs also exist for Python (resend on PyPI, now with async methods via httpx), PHP, Ruby, Go, Rust, Java, and .NET. codeAmani products are Node/Next.js, so this guide uses the Node SDK. The react property is Node-only.
Core Patterns
Send an email
from, to, and subject are required, plus one of html, text, react, or template. If you leave text out, Resend generates it from html.
// app/api/email/send/route.ts
import { Resend } from "resend";
import { NextRequest } from "next/server";
const resend = new Resend(process.env.RESEND_API_KEY);
export async function POST(req: NextRequest) {
const { to, subject, html } = (await req.json()) as {
to: string;
subject: string;
html: string;
};
const { data, error } = await resend.emails.send({
from: "codeAmani Labs <no-reply@codeamanilabs.org>",
to: [to],
subject,
html,
});
if (error) {
return Response.json({ error: error.message }, { status: error.statusCode ?? 500 });
}
return Response.json({ id: data.id });
}
| Field | Limit / rule |
|---|---|
to |
Up to 50 addresses. Every to/cc/bcc recipient counts as a separate email against your quota |
scheduledAt |
Natural language ("in 1 hour", "tomorrow at 9am ET") or ISO 8601, up to 30 days ahead |
attachments |
40 MB per email after Base64 encoding. content (Buffer/Base64) or path (URL), plus optional contentType and contentId for inline cid: images |
tags |
name/value may use ASCII letters, digits, _, and -, up to 256 chars |
headers |
Custom headers, e.g. List-Unsubscribe |
topicId |
Respects a contact's opt-out for that topic |
template |
{ id, variables }. Can't be combined with html/text/react |
Idempotency keys
Pass { idempotencyKey } as the second argument. The SDK sends it as the Idempotency-Key header. Resend keeps keys for 24 hours, and a key can be up to 256 characters. Use the format <event-type>/<entity-id>.
await resend.emails.send(
{ from, to, subject, react: WelcomeEmail({ userName, dashboardUrl }) },
{ idempotencyKey: `welcome-user/${userId}` },
);
A 409 invalid_idempotent_request means you reused a key with a different payload. Change the key. A 409 concurrent_idempotent_requests means the first request is still running. Retry it later.
React Email templates
npm install react-email react react-dom -E
npm install @react-email/ui -D -E # preview UI
Add "email:dev": "email dev" to package.json scripts and run npm run email:dev to preview at http://localhost:3000.
// emails/WelcomeEmail.tsx
import {
Body, Button, Container, Head, Heading,
Html, Preview, Section, Text,
} from "react-email";
interface WelcomeEmailProps {
userName: string;
dashboardUrl: string;
}
export function WelcomeEmail({ userName, dashboardUrl }: WelcomeEmailProps) {
return (
<Html lang="en">
<Head />
<Preview>Welcome to codeAmani Labs</Preview>
<Body style={{ backgroundColor: "#f6f9fc", fontFamily: "sans-serif" }}>
<Container style={{ margin: "0 auto", padding: "20px", maxWidth: "580px" }}>
<Heading>Welcome, {userName}!</Heading>
<Text>Your account is ready. Click below to get started.</Text>
<Section style={{ textAlign: "center", margin: "32px 0" }}>
<Button
href={dashboardUrl}
style={{ background: "#16a34a", color: "#fff", padding: "12px 24px", borderRadius: "6px" }}
>
Open Dashboard
</Button>
</Section>
</Container>
</Body>
</Html>
);
}
Two ways to send it:
- Pass the component to
reactand let the SDK render it. In a.tsfile, call it as a function:react: WelcomeEmail({ ... }). - Render the HTML yourself, for example to store or log it.
render()is async in React Email 6, so alwaysawaitit:
import { render } from "react-email";
import { WelcomeEmail } from "@/emails/WelcomeEmail";
const html = await render(
<WelcomeEmail userName={user.firstName} dashboardUrl={`${appUrl}/dashboard`} />,
);
await resend.emails.send({ from, to: [user.email], subject: "Welcome", html });
Resend Templates (dashboard-managed)
Product or ops teams can edit and publish a template in the Resend editor (it has version history), and your code sends it by id or alias:
await resend.emails.send({
from: "codeAmani Labs <receipts@codeamanilabs.org>",
to: [customerEmail],
subject: `Order ${orderId} confirmed`, // overrides the template default
template: { id: "order-confirmation", variables: { ORDER_ID: orderId, TOTAL: 499 } },
});
Only published templates can be sent. Variable keys may be up to 50 chars. FIRST_NAME, LAST_NAME, EMAIL, and UNSUBSCRIBE_URL are reserved. String values can be up to 2,000 chars. If a variable is missing, the API returns a validation error. Use React Email when the template lives in the repo. Use Templates when non-engineers own the copy.
Batch send
const { data, error } = await resend.batch.send(
receipts.map((r) => ({
from: "codeAmani Labs <receipts@codeamanilabs.org>",
to: [r.email],
subject: "Payment received",
html: r.html,
})),
{ idempotencyKey: `receipt-run/${runId}`, batchValidation: "permissive" },
);
// permissive: data.data = sent ids, data.errors = [{ index, message }]
Batch sends allow up to 100 emails per call, and the whole call counts as one request against the rate limit. They support tags, scheduledAt, template, and idempotency keys. They don't support attachments.
Schedule, reschedule, cancel
const { data } = await resend.emails.send({ from, to, subject, html, scheduledAt: "in 1 hour" });
if (data) {
await resend.emails.update({ id: data.id, scheduledAt: "tomorrow at 9am ET" });
await resend.emails.cancel(data.id); // a cancelled email can't be rescheduled
}
Clerk Webhook → Welcome Email Pattern
Send the welcome email automatically when Clerk creates a user. Clerk webhooks are Svix-signed, so verify them with svix and the Clerk signing secret.
svix 2.x changed
verify(). Insvix@2(2.8.0 now),Webhook.verify()returnsundefined. It no longer returns the parsed payload. Verify first, thenJSON.parsethe raw body yourself. Code written for svix 1.x that uses the return value getsundefinedand crashes. Resend's ownresend.webhooks.verify()still returns the parsed event.
// app/api/webhooks/clerk/route.ts
import { Webhook } from "svix";
import { Resend } from "resend";
import { WelcomeEmail } from "@/emails/WelcomeEmail";
const resend = new Resend(process.env.RESEND_API_KEY);
type ClerkUserCreated = {
type: string;
data: { id: string; first_name: string | null; email_addresses: { email_address: string }[] };
};
export async function POST(req: Request) {
const body = await req.text();
const headers = {
"svix-id": req.headers.get("svix-id") ?? "",
"svix-timestamp": req.headers.get("svix-timestamp") ?? "",
"svix-signature": req.headers.get("svix-signature") ?? "",
};
try {
// svix 2.x: verify() throws on a bad signature and returns undefined on success.
new Webhook(process.env.CLERK_WEBHOOK_SECRET ?? "").verify(body, headers);
} catch {
return new Response("Invalid signature", { status: 400 });
}
const event = JSON.parse(body) as ClerkUserCreated; // parse only after verifying
if (event.type === "user.created") {
const email = event.data.email_addresses[0]?.email_address;
if (email) {
await resend.emails.send(
{
from: "codeAmani Labs <welcome@codeamanilabs.org>",
to: [email],
subject: "Welcome to codeAmani Labs",
react: WelcomeEmail({
userName: event.data.first_name ?? "there",
dashboardUrl: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard`,
}),
},
{ idempotencyKey: `welcome-user/${event.data.id}` }, // Clerk retries are safe
);
}
}
return new Response("OK");
}
M-Pesa Receipt Emails (Kenya-targeted projects only)
When a Daraja STK Push succeeds, the callback delivers the MpesaReceiptNumber, amount, and transaction date. Send an email receipt as a secondary confirmation. Safaricom's SMS is the user's primary proof, so never block the callback on the email send. The email is a paper trail, not the source of truth.
Here is the flow from a successful payment to a sent receipt:
sequenceDiagram
participant D as "Daraja"
participant CB as "Callback route"
participant DB as "Database"
participant R as "Resend"
D->>CB: "STK callback · ResultCode 0"
CB->>DB: "upsert by CheckoutRequestID"
DB-->>CB: "inserted · receiptEmailSent false"
CB-->>D: "200 OK immediately"
CB->>R: "send PaymentReceipt · idempotencyKey"
R-->>CB: "email id"
CB->>DB: "set receiptEmailSent true"
PaymentReceipt Template
The amount is shown with a KES prefix because Daraja amounts are whole shillings. The MpesaReceiptNumber is the reference users quote to support.
// emails/PaymentReceipt.tsx
import {
Body, Column, Container, Head, Heading, Hr,
Html, Preview, Row, Section, Text,
} from "react-email";
interface PaymentReceiptProps {
customerName: string;
amount: number; // integer KES
mpesaReceiptNumber: string;
transactionDate: string; // already formatted for display (EAT)
description: string;
}
export function PaymentReceipt({
customerName,
amount,
mpesaReceiptNumber,
transactionDate,
description,
}: PaymentReceiptProps) {
const rows: [string, string][] = [
["Amount", `KES ${amount.toLocaleString("en-KE")}`],
["M-Pesa receipt", mpesaReceiptNumber],
["Date", transactionDate],
["For", description],
];
return (
<Html lang="en">
<Head />
<Preview>Payment received: KES {amount.toLocaleString("en-KE")}</Preview>
<Body style={{ backgroundColor: "#f6f9fc", fontFamily: "sans-serif" }}>
<Container style={{ margin: "0 auto", padding: "20px", maxWidth: "580px" }}>
<Heading>Payment received</Heading>
<Text>Hi {customerName}, your M-Pesa payment was successful.</Text>
<Section style={{ background: "#fff", borderRadius: "8px", padding: "20px" }}>
{rows.map(([label, value], i) => (
<Section key={label}>
{i > 0 && <Hr style={{ borderColor: "#e5e7eb", margin: "12px 0" }} />}
<Row>
<Column style={{ color: "#6b7280" }}>{label}</Column>
<Column style={{ textAlign: "right", fontWeight: i === 0 ? 700 : 400 }}>{value}</Column>
</Row>
</Section>
))}
</Section>
<Text style={{ color: "#6b7280", fontSize: "12px", marginTop: "16px" }}>
Keep this receipt for your records. Powered by codeAmani Labs.
</Text>
</Container>
</Body>
</Html>
);
}
Send on the Daraja Callback
// app/api/mpesa/callback/route.ts
import { Resend } from "resend";
import { PaymentReceipt } from "@/emails/PaymentReceipt";
import { NextRequest } from "next/server";
const resend = new Resend(process.env.RESEND_API_KEY);
type StkItem = { Name: string; Value?: string | number };
type StkCallback = {
ResultCode: number;
CheckoutRequestID: string;
CallbackMetadata?: { Item: StkItem[] };
};
type PaidTxn = {
firstTime: boolean;
customerName: string;
customerEmail: string | null;
amount: number;
mpesaReceiptNumber: string;
transactionDate: string;
description: string;
checkoutRequestId: string;
};
// Your DB helpers: upsert by CheckoutRequestID and report whether this was the first write.
declare function markPaidIfNew(
checkoutRequestId: string,
p: { amount: number; mpesaReceiptNumber: string },
): Promise<PaidTxn>;
declare function logError(scope: string, err: unknown): void;
export async function POST(req: NextRequest) {
const body = (await req.json()) as { Body: { stkCallback: StkCallback } };
const cb = body.Body.stkCallback;
// Always ACK Daraja fast. Don't block on DB or email work.
if (cb.ResultCode !== 0 || !cb.CallbackMetadata) {
return Response.json({ ResultCode: 0, ResultDesc: "Accepted" });
}
// Look metadata items up by Name. Their order isn't guaranteed.
const items = cb.CallbackMetadata.Item;
const get = (name: string) => items.find((i) => i.Name === name)?.Value;
const txn = await markPaidIfNew(cb.CheckoutRequestID, {
amount: Number(get("Amount")),
mpesaReceiptNumber: String(get("MpesaReceiptNumber")),
});
if (txn.firstTime && txn.customerEmail) {
// Fire-and-forget: a Resend error must never fail the callback ACK.
sendReceipt(txn, txn.customerEmail).catch((err) => logError("receipt-email", err));
}
return Response.json({ ResultCode: 0, ResultDesc: "Accepted" });
}
async function sendReceipt(txn: PaidTxn, to: string) {
const { error } = await resend.emails.send(
{
from: "codeAmani Labs <receipts@codeamanilabs.org>",
to: [to],
subject: `Payment received: KES ${txn.amount.toLocaleString("en-KE")}`,
react: PaymentReceipt({
customerName: txn.customerName,
amount: txn.amount,
mpesaReceiptNumber: txn.mpesaReceiptNumber,
transactionDate: txn.transactionDate,
description: txn.description,
}),
},
// Belt and suspenders: Resend dedupes this key for 24 h even if the app gate races.
{ idempotencyKey: `mpesa-receipt/${txn.checkoutRequestId}` },
);
if (error) throw new Error(`${error.name}: ${error.message}`);
}
Gotcha: idempotent send, non-blocking ACK. Daraja may deliver the same callback more than once. Gate the email behind a "first time we marked this
CheckoutRequestIDpaid" check, and also pass a Resend idempotency key. Send fire-and-forget. A failed receipt email must never turn a successful payment into a failed-looking callback. On a serverless platform, useafter()fromnext/server(or a queue) so the send isn't cut off when the response returns.
Webhooks (Delivery Events + Inbound)
Resend signs webhooks with Svix. Verify them with the SDK's built-in resend.webhooks.verify(). You don't need a separate svix package for Resend webhooks. Pass the raw body and the three svix-* headers:
// app/api/webhooks/resend/route.ts
import { Resend } from "resend";
import { NextRequest, NextResponse } from "next/server";
const resend = new Resend(process.env.RESEND_API_KEY);
export async function POST(req: NextRequest) {
const payload = await req.text(); // raw body: required
const id = req.headers.get("svix-id");
const timestamp = req.headers.get("svix-timestamp");
const signature = req.headers.get("svix-signature");
const webhookSecret = process.env.RESEND_WEBHOOK_SECRET;
if (!id || !timestamp || !signature || !webhookSecret) {
return new NextResponse("Missing headers", { status: 400 });
}
let event: ReturnType<typeof resend.webhooks.verify>;
try {
event = resend.webhooks.verify({ payload, headers: { id, timestamp, signature }, webhookSecret });
} catch {
return new NextResponse("Invalid webhook", { status: 400 });
}
switch (event.type) {
case "email.bounced":
case "email.complained":
// Stop mailing this address in your app. Resend also suppresses it.
break;
case "email.received": {
// Inbound payloads carry metadata only. Fetch the body separately.
const { data: email } = await resend.emails.receiving.get(event.data.email_id);
void email; // email.html, email.text, email.headers
break;
}
}
return new NextResponse("OK");
}
See examples/webhook-route.ts for the full version, which dedupes on svix-id and handles more event types.
Email event types: email.sent, email.scheduled, email.delivered, email.delivery_delayed, email.bounced, email.complained, email.failed, email.suppressed, email.opened, email.clicked, email.received. Resend also sends domain.*, contact.* (plus contact.topics.updated), topic.*, suppression.added/removed, and inbox.* (beta) events.
Retries: Resend retries immediately, then after 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, and 10 h. An endpoint that keeps failing is disabled automatically, and Resend emails your team. You can replay messages from the dashboard. Return 2xx quickly and dedupe on svix-id. You can also manage endpoints in code with resend.webhooks.create/list/update/remove/rotateSigningSecret.
Inbound Email
- Enable Receiving on a verified domain. Use a subdomain such as
inbound.codeamanilabs.org, because Resend receives all mail for whatever domain its MX record points at. For testing, you can use your account's<id>.resend.appaddress. - Add the MX record Resend shows you. For us-east-1 it's
inbound-smtp.us-east-1.amazonaws.com, priority 10. - Subscribe a webhook to
email.received. Fetch the content withresend.emails.receiving.get(id)and attachments with the received-attachments API. Forward withresend.emails.receiving.forward(...).
Every received email counts toward the monthly quota, and toward the daily quota on the Free plan.
Marketing: Contacts, Segments, Topics, Broadcasts
| Concept | What it is | SDK |
|---|---|---|
| Contact | One global record per email address | resend.contacts.create({ email, segments, topics }) |
| Segment | Internal list you send to (formerly "Audience") | resend.segments.create({ name }) |
| Topic | User-facing preference that contacts can opt out of | resend.topics.create({ name, defaultSubscription }) |
| Broadcast | A campaign sent to a segment | resend.broadcasts.create({ segmentId, ..., send: true }) |
const { data } = await resend.broadcasts.create({
segmentId,
topicId, // only contacts opted in to this topic receive it
from: "codeAmani Labs <news@codeamanilabs.org>",
subject: "What we shipped in October",
html: 'Hi {{{contact.first_name|there}}} … <a href="{{{RESEND_UNSUBSCRIBE_URL}}}">Unsubscribe</a>',
send: true, // omit to create a draft
scheduledAt: "tomorrow at 9am ET",
});
Marketing mail requires recorded consent, an unsubscribe link, and a separate sending subdomain (for example news.codeamanilabs.org) with open tracking enabled only there. Full example: examples/marketing-broadcast.ts.
Automations: build the flow in the dashboard, then trigger it from code with resend.events.send({ event: "user.created", email, payload }). Plans include 10,000 runs a month. On paid plans, each extra run costs $0.0015.
Domain Setup & Deliverability
A verified domain is required to send anything except test mail. Resend's DNS records:
| Record | Host | Value | Purpose |
|---|---|---|---|
| TXT (DKIM) | resend._domainkey |
p=… public key from the dashboard |
Signs mail |
| MX | send |
feedback-smtp.<region>.amazonses.com, priority 10 |
Return path (bounces) |
| TXT (SPF) | send |
v=spf1 include:amazonses.com ~all |
Authorizes the return-path domain |
| TXT (DMARC) | _dmarc |
v=DMARC1; p=none; rua=mailto:dmarc@yourdomain |
Recommended. Tighten to quarantine, then reject |
| MX (inbound, optional) | inbound (a subdomain) |
inbound-smtp.<region>.amazonaws.com, priority 10 |
Receiving |
SPF and MX go on the
send.subdomain, not on the apex. If you putinclude:amazonses.comon@, you can clash with your mailbox provider's SPF, and it does nothing for Resend alignment. DKIM onresend._domainkeyis what aligns with your From domain for DMARC. This matches../domain-portfolio/and../porkbun/. When you paste into Porkbun or Cloudflare, enter only the host part (send, notsend.example.com).
flowchart TD
A["Add domain or subdomain in Resend"] --> B["Copy DKIM + send. MX/SPF"]
B --> C["Add records at DNS host (Porkbun / Cloudflare)"]
C --> D["Verify in dashboard"]
D --> E{"Verified?"}
E -->|"yes"| F["Add _dmarc, send from domain"]
E -->|"no"| G["Check host field, wait, re-verify"]
G --> D
Deliverability rules:
- Send from subdomains (
mail.,news.), not the apex. Resend recommends this so a reputation problem stays contained. Keep transactional and marketing mail on separate subdomains. - Open/click tracking is off by default. Leave it off for transactional domains. Inbox providers can read tracked mail as marketing.
- Region: choose
us-east-1(default),eu-west-1,sa-east-1, orap-northeast-1per domain. Region controls where mail is sent from, not where data is stored. Account data stays in the US. To change a domain's region, delete the domain and add it again. - Gmail / Yahoo / Microsoft bulk-sender rules apply once you send about 5,000 messages a day to their consumer inboxes. They require SPF and DKIM, DMARC at
p=noneor stricter aligned with From, RFC 8058 one-click unsubscribe (List-Unsubscribe+List-Unsubscribe-Post: List-Unsubscribe=One-Click) on marketing mail, unsubscribes honored within 2 days, and a spam rate below 0.3%. Microsoft has rejected non-compliant mail with550 5.7.515since May 2025. See the full table in../domain-portfolio/CLAUDE_CODE_INTEGRATION.md. - Resend's own thresholds: keep bounces under 4% and spam complaints under 0.08%, or sending may be paused.
Limits & Pricing (snapshot 2026-10-20)
| Limit | Value |
|---|---|
| API rate limit | 10 req/s per team (shared across keys). A 429 comes with ratelimit-* and retry-after headers |
| Free daily quota | 100 emails/day (UTC calendar day). Sent and received mail both count |
| Recipients per send | 50 |
| Emails per batch | 100, no attachments |
| Attachments | 40 MB per email after Base64 encoding |
| Scheduling window | 30 days |
| Idempotency key | 24 h retention, 256 chars |
| Data retention | 30 days (Enterprise is flexible) |
| Overage cap | Pay-as-you-go stops at 5× the monthly quota |
| Transactional plan | Price | Emails/mo | Domains | Overage per 1,000 |
|---|---|---|---|---|
| Free | $0 | 3,000 (100/day) | 3 | n/a |
| Pro | $20 / $35 | 50,000 / 100,000 | 10 | $0.90 |
| Scale | from $90 | 100,000 to 2.5M | 1,000 | $0.90 down to $0.46 |
| Enterprise | custom | custom | contract | custom |
Marketing plans bill by contacts: Free covers 1,000 contacts, and Pro Marketing starts at $40/mo for 5,000. Add-ons: a dedicated IP costs $30/mo (Scale, more than 3,000 emails/day), and 100 extra domains cost $20/mo. Each inbox beyond the 3 included costs $1/mo. See reference/limits-and-pricing.md.
MCP Server, CLI & Agent Skills
| Tool | How to use it |
|---|---|
| Remote MCP (OAuth) | https://mcp.resend.com/mcp. Claude.ai connector directory, or claude plugin install resend@claude-plugins-official (MCP + Resend skills), then /mcp → resend to log in |
| Remote MCP (headless) | claude mcp add --transport http resend https://mcp.resend.com/mcp --header "Authorization: Bearer <key>" |
| Local MCP | npx -y resend-mcp (stdio). --http --port 3000 for HTTP. --sender and --reply-to set defaults |
| CLI | npm i -g resend-cli, then resend emails send, resend emails batch --batch-validation permissive, resend domains, resend suppressions |
| Skills | npx skills add resend/resend-skills (resend, react-email, email-best-practices) |
Agent safety. An API key with full access lets an agent send mail as your domain. For local MCP, create a sending-only API key restricted to one domain, and keep it in the secrets vault (Hazina), never in a committed
.mcp.json. In this workspace the claude.ai Resend connector needs OAuth before it works.
Environment Variables
Secrets (store them in the secrets vault, .env.local for development, and Vercel for deploys):
RESEND_API_KEY=re_...
RESEND_WEBHOOK_SECRET=whsec_...
Non-secret settings:
| Variable | Example | Notes |
|---|---|---|
EMAIL_FROM |
codeAmani Labs <no-reply@codeamanilabs.org> |
Must be on a verified domain |
NEXT_PUBLIC_APP_URL |
https://app.example.com |
Used for links inside emails |
Common Use Cases
| Use Case | Approach |
|---|---|
| Welcome / onboarding | WelcomeEmail.tsx triggered by Clerk user.created (idempotency key = Clerk user id) |
| Stripe receipt / subscription confirmation | Send from the Stripe webhook handler after verifying the signature. Idempotency key = Stripe event id |
| M-Pesa receipt (Kenya projects) | PaymentReceipt.tsx from the Daraja callback, fire-and-forget |
| Password reset / magic link | Use Clerk's built-in email. Point Clerk's custom SMTP at Resend only if you need your own branding |
| Support inbox | Inbound on inbound. subdomain → email.received → emails.receiving.get |
| Newsletter | Segment + Topic + Broadcast on a news. subdomain |
| System alerts | Plain html. No template needed |
codeAmani notes
- Server-side only.
RESEND_API_KEYstays in route handlers, server actions, and workers. Never put it in aNEXT_PUBLIC_variable or a client component. If a key leaks, Resend's GitHub secret scanner revokes it automatically. Rotate it in the vault right away. - Default sending domain:
codeamanilabs.org(DNS on Cloudflare; DKIMresend._domainkey, SPF/MX onsend., DMARCp=quarantine). New products should verify their own subdomain (for examplemail.<product>.com). - Verify every webhook before acting on it:
resend.webhooks.verify()for Resend,svixfor Clerk, and the Stripe signing secret for Stripe. This follows CLAUDE.md. - Payments: Stripe is the default, and receipt emails hang off the Stripe webhook. M-Pesa receipt emails apply only to Kenya-targeted projects.
- AI-written email: when Claude drafts copy (summaries, digests), generate it server-side, sanitize any HTML from user content with DOMPurify before you put it in a template, and keep a human-readable
textpart. - African market: for Kenya-targeted products, email is a secondary channel behind SMS (Africa's Talking) and WhatsApp. Keep emails light (inline CSS, few images) for 2G/3G users, and format money as
KES 1,500. - Compliance: marketing mail needs consent, an unsubscribe link, and a physical address under CAN-SPAM (US). For Kenya projects, KDPA 2019 applies. Never put PII in tags or idempotency keys. Use opaque ids.
Troubleshooting
| Issue | Fix |
|---|---|
401 / validation_error on key |
Key must start with re_. Check that the key's permission covers the endpoint (sending-only keys can't manage domains) |
403 domain mismatch |
The from domain isn't verified, or the key is restricted to another domain. onboarding@resend.dev only delivers to your own address |
429 rate_limit_exceeded |
More than 10 req/s per team. Batch the sends, queue them, and honor retry-after |
429 daily_quota_exceeded / monthly_quota_exceeded |
Free plan allows 100/day (UTC). Received mail counts too. Upgrade, or wait for midnight UTC |
409 idempotency |
Key reused with a different body (change the key), or a concurrent request (retry later) |
| Emails go to spam | Check DKIM, send. SPF/MX, and DMARC alignment. Send from a subdomain. Turn tracking off for transactional mail |
| Domain stuck "pending" | The host field includes the domain twice (send.example.com.example.com). Paste only send. Allow up to 72 h |
| Webhook 400 | Use the raw req.text() body (never parsed JSON) and all three svix-* headers. Use the secret from that specific endpoint |
| Webhook endpoint disabled | It failed repeatedly. Fix the endpoint, re-enable it in the dashboard, then replay the failed messages |
Cannot find module '@react-email/components' |
Install react-email and change the imports. The old package is deprecated |
| Inbound webhook has no body | Expected. Call resend.emails.receiving.get(email_id) |
Official docs: