Email Integration
Send typed React Email templates through any email service. smtp() works with Postmark, Resend,
Amazon SES, SendGrid, Mailgun, a company relay, or a local test inbox. resend() uses Resend's API
and adds scheduling, idempotency keys, and webhooks.
Start with smtp(). Switch to resend() when you need what only Resend's API offers.
Send through any provider
import { smtp, template } from "@farm.js/email/smtp";
function WelcomeEmail({ name }: { name: string }) {
return <p>Hello {name}</p>;
}
export const email = smtp({
// Reads SMTP_USER and SMTP_PASS.
service: "postmark",
defaults: { from: "hello@example.com" },
templates: {
// The component comes first, so `data` is typed from its props.
welcome: template(WelcomeEmail, { subject: "Welcome to Farm.js" }),
},
// Required: the mounted routes send from your domain.
authorize: async (request) => Boolean(await getSessionUser(request)),
});await apiClient.email.send.post({
body: {
templateId: "welcome",
to: "ada@example.com",
data: { name: "Ada" },
},
});templateId and data are checked against your templates at compile time. Changing providers
changes the service line and the credentials, never a caller.
Name your provider
service takes any of the 92 names nodemailer 10.6 knows, and a typo is a type error. The common
transactional providers:
| Provider | service | SMTP_USER | SMTP_PASS |
|---|---|---|---|
| Postmark | "postmark" | Server API token | Server API token |
| Resend | "resend" | resend | API key |
| SendGrid | "sendgrid" | apikey | API key |
| Amazon SES | "ses-us-east-1" (your region) | SES SMTP username | SES SMTP password |
| Mailgun | "mailgun" | Domain SMTP login | Domain SMTP password |
The full list is exported as SMTP_SERVICES. Pass auth: { user, pass } to read credentials from
somewhere other than the environment.
Connect to any server
For a server nodemailer doesn't name, pass host. With no service or host, smtp() reads
everything from the environment.
smtp({ host: "smtp.example.com", port: 587, templates, authorize });
smtp({ templates, authorize }); // SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS| Variable | Purpose |
|---|---|
SMTP_HOST | Server host when neither service nor host is set. |
SMTP_PORT | Server port. Defaults to 465 when secure, otherwise 587. |
SMTP_USER | Login user. Set it together with SMTP_PASS, or set neither. |
SMTP_PASS | Login password or API key. |
SMTP_FROM_EMAIL | Default sender when a template and defaults.from set none. |
SMTP_REPLY_TO_EMAIL | Default reply-to address. |
smtp() reports every configuration problem at once when the app starts: an unknown service,
service together with host, a port outside 1-65535, or a user without a password.
Mail never crosses the network in plaintext. Port 465 uses implicit TLS, and any other port must
upgrade with STARTTLS or the send fails. Only loopback hosts (localhost, 127.0.0.1, ::1) may
skip TLS, so a local Mailpit or MailDev inbox works in development.
Implement the delivery layer yourself
instance replaces the connection with your own delivery layer. It is any object with a sendMail
method. Farm.js renders the template, checks the request, and hands you a finished message:
// Exported from @farm.js/email/smtp.
interface SmtpIntegrationInstance {
sendMail(message: SmtpMessage): Promise<SmtpSentMessage>;
}
// SmtpMessage: { from, to, cc?, bcc?, replyTo?, subject, html, text, attachments? }
// SmtpSentMessage: { messageId, accepted?, rejected? }A nodemailer transporter already has that shape, so pooling, OAuth2, DKIM signing, and proxies all come from nodemailer's own options:
import { createTransport } from "nodemailer";
export const email = smtp({
instance: createTransport({
pool: true,
host: "smtp.example.com",
port: 465,
secure: true,
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
}),
templates,
authorize,
});Or write it yourself. This outbox keeps messages in memory for tests:
import { smtp, type SmtpMessage } from "@farm.js/email/smtp";
export const outbox: SmtpMessage[] = [];
export const email = smtp({
instance: {
async sendMail(message) {
outbox.push(message);
return { messageId: `<${outbox.length}@test.local>`, accepted: message.to };
},
},
templates,
allowUnauthenticated: true,
});The same method can call a provider's HTTP API, which is the way to send from a runtime without TCP
sockets. Forward every field you receive (cc, bcc, replyTo, attachments); Farm.js has already
checked them. Farm.js closes the transport it creates when the integration is disposed and never
closes an instance you pass.
What SMTP leaves out
| Area | smtp() | resend() |
|---|---|---|
| Providers | Any SMTP server, or your own instance | Resend |
| Send, preview, templates | Yes | Yes |
| Schedule route | No | Yes |
idempotencyKey | Refused with 400 | Passed to Resend |
tags, topicId | Refused with 400 | With allowCallerHeaders |
| Delivery webhooks | Configure them in your provider | webhooks option |
| Attachments | Inline base64 content only | content or a path URL |
| Send result | Resend's fields, plus accepted and rejected | id, templateId, to, subject |
When the server refuses some recipients, the send still succeeds and lists them in rejected. When
it refuses all of them or can't be reached, the route answers 502 with the SMTP error code, such
as EENVELOPE or ESOCKET. The server's full reply goes to the server log, not to the caller.
Send through Resend
resend() lives in @farm.js/email and takes the same templates, defaults, and authorize.
import { resend, template } from "@farm.js/email";
export const email = resend({
apiKey: process.env.RESEND_API_KEY,
defaults: { from: "hello@example.com" },
templates,
// Required: the mounted routes spend your Resend credits.
authorize: async (request) => Boolean(await getSessionUser(request)),
});Choose SDK ownership
When instance is omitted, Farm.js creates the Resend SDK from apiKey, supplied directly or through
RESEND_API_KEY. To share an SDK object your application already owns, pass it as instance:
import { Resend } from "resend";
import { resend } from "@farm.js/email";
const resendClient = new Resend(process.env.RESEND_API_KEY);
export const email = resend({
instance: resendClient,
defaults: { from: "hello@example.com" },
templates,
});The instance wins if an API key is also supplied. Templates, defaults, scheduling, previews, routes, and webhooks remain integration options in either mode.
What Resend adds
| Area | Details |
|---|---|
| Templates | Typed React Email templates with subjects, preview text, defaults, and preview props. |
| Send | A typed send route for transactional messages. |
| Schedule | A typed route for future delivery. |
| Preview | HTML and text rendering for local previews or admin tools. |
| Templates index | A route that lists configured templates and preview metadata. |
| Webhooks | Optional Resend webhook receivers for delivery events. |
Schedule mail
await api.email.schedule.post({
body: {
templateId: "welcome",
to: "ada@example.com",
when: "tomorrow 9am",
data: {
name: "Ada",
},
},
});Preview before sending
Both integrations mount the preview route.
const preview = await api.email.preview.post({
body: {
templateId: "welcome",
data: {
name: "Ada",
},
},
});
console.log(preview.data?.subject);
console.log(preview.data?.html);Template defaults
Templates can supply their own subject, previewText, from, and replyTo. The integration also supports global defaults, which keeps common sender details out of every call.
function InviteEmail({ workspace }: { workspace: string }) {
return <p>Join {workspace}</p>;
}
const templates = {
invite: template(InviteEmail, {
subject: ({ workspace }) => `Join ${workspace}`,
previewText: "You were invited to collaborate.",
}),
};Authorize the routes
Configuring either integration mounts POST /api/email/send and /preview under your app's own
origin, and resend() adds /schedule. Those routes send from your domain and spend your
provider's quota, so they refuse anonymous callers: without authorize they answer 401 and
nothing is sent.
authorize receives the request and the route being called. Return true to allow, false for a
generic 401, or a Response to answer the caller yourself.
export const email = resend({
apiKey: process.env.RESEND_API_KEY,
templates,
authorize: async (request, { route }) => {
const user = await getSessionUser(request);
if (!user) return false;
// Only staff may schedule campaigns; any signed-in user may send.
return route === "schedule" ? user.isStaff : true;
},
});smtp() has no schedule route, so its route is "send" or "preview", and checking for
"schedule" is a type error.
Farm.js also rejects cross-site callers before authorize runs, so a session-cookie check cannot be
turned into a forged send by another site. Add extra trusted origins with allowedOrigins, using
the same syntax as serverActions.allowedOrigins.
If the base path is already gated by your own middleware or at the edge, opt out explicitly:
resend({ templates, allowUnauthenticated: true });The recipient (to) and template data come from the request body, so authorize is where you
decide who may address mail to whom. to may be an array, so check every recipient there, not
only the first. The sender, copy, and attachment fields (from, replyTo, cc, bcc,
attachments, tags, topicId) come from your template and defaults configuration: a request
that sets any of them is rejected with 400, so a caller allowed to send a template cannot send
it as someone else, copy it to extra recipients, or attach files. Resend fetches an attachment's
path URL itself, so a caller-chosen attachment can pull any URL into your mail. To let trusted
callers choose these fields, opt in:
resend({ templates, authorize, allowCallerHeaders: true });smtp() accepts the same opt-in. Even then, its attachments must be inline base64 content: it
never reads a file path from the server's disk or fetches a URL.
Production notes
- For
smtp(), set the provider's SMTP credentials andSMTP_FROM_EMAILon a domain the provider has verified. Forresend(), setRESEND_API_KEYand a verifiedRESEND_FROM_EMAIL. smtp()needs a runtime with TCP sockets. Farm.js has verified it on Node. Elsewhere, pass aninstancethat calls your provider's HTTP API.- Use Resend's idempotency keys for important transactional flows.
- Preview templates in development before sending them to real recipients.
- Keep template IDs stable because they are part of the caller contract.
- Verify webhooks before using delivery events for product logic.
Send typed React Email templates through any SMTP provider, or through Resend for scheduling and webhooks.