Client reference
Exact construction options, methods, routing helpers, validation results, and send results for the v1 client.
createEmailClient(options)
Construction is synchronous and requires at least one adapter after plugins register their routes.
type EmailClientOptions<Adapters, Plugins> = {
adapters?: Adapters;
defaultAdapter?: Adapters[number]["name"];
fallback?: EmailFallbackConfig<Adapters[number]["name"]>;
retry?: EmailRetryConfig;
hooks?: EmailHooks;
plugins?: Plugins;
telemetry?: boolean;
};
| Option | Default | Behavior |
|---|---|---|
adapters |
[] |
Literal-named adapter routes. Plugins may add routes. |
defaultAdapter |
First registered adapter | Primary route for operations without an override. |
fallback |
No fallback | Candidate adapters and unknown-delivery policy. |
retry |
{ maxAttempts: 1 } |
Client-level retry policy. |
hooks |
None | Best-effort lifecycle observers. |
plugins |
[] |
Synchronous route, hook, middleware, and extension composition. |
telemetry |
true |
Anonymous SDK analytics unless an environment opt-out applies. |
Duplicate adapter names, duplicate plugin ids, unknown default/fallback names, maxAttempts < 1, async plugin adapters, and extension-key collisions throw during construction.
Client properties
readonly adapters: ReadonlyMap<RouteName, EmailAdapter>;
readonly defaultAdapter: RouteName;
validate(message, options?)
Runs common message, route, capability, adapter-specific, schedule, and personalized checks without calling an adapter’s send method.
type EmailValidationResult<Name extends string> = {
adapter: Name;
warnings: readonly { code: string; message: string }[];
};
Built-in validation currently returns an empty warnings array on success.
send(message, options?)
type EmailSendOptions<
Name extends string = string,
Native extends EmailNativeOptionsMap = never,
> = [Native] extends [never]
? EmailSendOptionsBase<Name>
: EmailSendOptionsBase<Name> & { native?: Native }; // experimental, keyed by adapter name
type EmailSendOptionsBase<Name extends string> = {
adapter?: Name;
fallback?: {
adapters: readonly Name[];
onUnknownDelivery?: "stop" | "continue";
};
retry?: {
maxAttempts?: number;
delay?: (attempt: number, error: EmailSdkError) => number;
shouldRetry?: (error: EmailSdkError, attempt: number) => boolean;
};
signal?: AbortSignal;
idempotencyKey?: string;
idempotency?: "strict" | "best-effort";
metadata?: EmailSendMetadata;
};
native carries provider-specific options; each adapter receives only its own entry. The client’s send() fills Native with EmailNativeOptions<typeof adapters>, so native is typed from its adapters. A bare EmailSendOptions<Name> annotation leaves Native as never and has no native field, so code written before it existed still compiles. To accept native options in your own helper, type the parameter as Parameters<typeof email.send>[1]. See Use provider-native features.
idempotency controls what idempotencyKey requires. With "strict", the default, a route that includes an adapter whose capabilities.idempotency is "none" fails with EmailValidationError before any request, so a key is never dropped silently. "best-effort" sends anyway and forwards the key to adapters that use it.
Per-send retry and fallback objects replace the client objects. adapter selects the primary route. metadata is lifecycle context, separate from provider-facing message.metadata. The SDK passes an isolated copy of plain data (and a fresh error or response snapshot including cloned accepted/rejected arrays) to each observational hook (beforeSend hooks, afterSend, onError, onRetry), afterSend/onError middleware item, and adapter attempt, while beforeSend middleware transforms share the in-flight cloned options down the transform chain without mutating the caller’s object. Plain objects, null-prototype chains, arrays (including enumerable symbol keys), Date, Map, Set, DataView, typed arrays, ArrayBuffer, SharedArrayBuffer, RegExp, and URL are cloned (up to 128 levels deep) so mutations in one observational callback cannot leak into other callbacks, retries, fallbacks, or the caller. Custom class instances in metadata and provider-opaque response.raw or error.cause values are passed by reference so private fields, methods, and native error causes stay intact; wrap shared callback state in a custom class instance if hooks need to communicate via metadata.
By default EmailSendMetadata is EmailMetadataRecord: strings, numbers, booleans, null, undefined, Date, and arrays or plain objects of those. To give it your own shape, augment EmailMetadataRegister once in your app:
// The import makes this file a module, so the block below augments the SDK types instead of replacing them.
import "@opencoredev/email-sdk";
declare module "@opencoredev/email-sdk" {
interface EmailMetadataRegister {
metadata: { tenantId: string; traceId?: string };
}
}
After that, send() requires that shape and hooks read event.metadata?.tenantId as a string.
type EmailSendResult<Name extends string = string, Raw = unknown> = {
adapter: Name;
id?: string;
accepted?: readonly string[];
rejected?: readonly string[];
raw?: Raw;
};
sendMany(items, options?)
type EmailSendItem<Name extends string = string, Native extends EmailNativeOptionsMap = never> = {
message: EmailMessage;
options?: EmailSendOptions<Name, Native>;
};
type EmailSendManyOptions<
Name extends string = string,
Native extends EmailNativeOptionsMap = never,
> = EmailSendOptions<Name, Native> & { concurrency?: number };
type EmailSendSettledResult<Name extends string> =
| { ok: true; index: number; result: EmailSendResult<Name> }
| { ok: false; index: number; error: EmailSdkError };
Items run one at a time in input order unless the method options set concurrency (a positive integer, default 1), which caps how many items send at once. Results are always in input order. concurrency applies to the batch only and is not passed to each send. Item options override method options. When method options set a non-blank idempotencyKey, each item without its own idempotencyKey derives <key>:<index> so providers do not deduplicate distinct items against each other; a blank or non-string shared idempotencyKey is rejected per item unless that item supplies its own valid key. retry and fallback merge one level deep, so an item that sets only retry.delay keeps the method’s retry.maxAttempts; an item’s fallback.adapters still replaces the method’s list. An item’s native entry for an adapter replaces the method’s entry for that adapter and keeps the others. The method returns one settled result per item once input validation passes; non-array items, non-object options, or invalid concurrency reject the call with EmailValidationError.
sendPersonalized(input, options?)
type EmailPersonalizedInput = {
message: Omit<EmailMessage, "to" | "cc" | "bcc">;
recipients: readonly {
to: EmailAddress;
variables: Readonly<Record<string, string | number | boolean>>;
}[];
};
At least one accepted recipient resolves with accepted and rejected. Zero accepted recipients throws EmailAllRecipientsFailedError.
adapter(name)
Returns the exact adapter type for a registered literal name. Unknown runtime names throw EmailAdapterNotFoundError.
withAdapter(name)
Returns validate, send, sendMany, and sendPersonalized bound to one adapter.
const backup = email.withAdapter("backup");
await backup.send(message);
flush()
Waits for in-flight opt-out telemetry and never rejects. Serverless runtimes freeze the process on response and drop those requests, so await this (or pass it to waitUntil) before a handler returns. Long-running servers do not need it, and it resolves immediately when telemetry is disabled.
await email.send(message);
waitUntil(email.flush());
Performance
The SDK’s own work on a send is small next to the provider’s network round trip. A client with no plugins or hooks skips the empty lifecycle steps, and telemetry data is only built when telemetry is on.
The repository’s overhead benchmark compares each send with a hand-built request to the same mock fetch, with telemetry off. One run on Bun 1.4.4 measured:
| Case | SDK | Hand-built | SDK adds |
|---|---|---|---|
Resend send |
1.59 µs | 0.83 µs | 0.76 µs |
Postmark send |
1.70 µs | 0.80 µs | 0.90 µs |
SendGrid send |
1.91 µs | 0.71 µs | 1.20 µs |
SES send, both sides cache the SigV4 key |
24.88 µs | 27.49 µs | within noise |
Resend sendMany, 20 messages |
35.97 µs | 18.18 µs | 17.79 µs |
New client with resend() |
0.28 µs | 0.02 µs | 0.25 µs |
SES time is almost all SigV4 hashing. The adapter reads credentials from its options on every send, so refreshed STS credentials apply to the next request, and caches only the derived signing key for each secret, UTC day, region, and service.
These are microbenchmark numbers from one machine. To measure your own, see the benchmark README.
Message reference
Look up every normalized message field.
Error reference
Handle the closed v1 error union.