yatta/mail
Templates, layouts, transports, and preview sending.
34 exported symbols and 175 members, read from src/types/mail.ts.
Construct
assertEmailSent
functionConvenience assertion helper verifying that an email matching criteria was dispatched.
assertEmailSent(mailer: YattaMailer, filter: { to?: string; subject?: string | RegExp; contains?: string; }): void- mailer
- Host mailer instance.
- filter
- Matcher criteria (`to`, `subject`, `contains`).
assertEmailSent(mailer, { to: "alice@example.com", subject: /Welcome/i });assertNoCrlf
functionAsserts that a string does not contain Carriage Return (`\r`) or Line Feed (`\n`) characters.
assertNoCrlf(value: string, fieldName: string): void- value
- String value to validate.
- fieldName
- Descriptive field name for error reporting.
assertNoCrlf("Subject line", "Subject"); // PassesassertNoCrlf("Subject\nBcc: hacker@evil.com", "Subject"); // Throws YattaMailErrorcreateMailer
functionCreates and configures a new instance and registers it as the global default.
createMailer<TTemplates extends Record<string, Record<string, unknown>> = RegisteredTemplates>(options?: MailerOptions<TTemplates>): YattaMailer<TTemplates>- options
- Mailer configuration options.
Returns Configured `YattaMailer` instance.
export const mailer = createMailer({ provider: "resend", auth: { user: "resend", pass: process.env.RESEND_API_KEY! }, defaultFrom: "Yatta <noreply@yatta.dev>"});escapeHtml
functionEscapes HTML control characters (`&`, `<`, `>`, `"`, `'`) in dynamic text values to prevent XSS.
escapeHtml(value: unknown): string- value
- Dynamic value to escape.
Returns Safe HTML string with entities encoded.
expectEmail
functionFluent assertion helper for verifying dispatched emails during tests in `"memory"` mode.
expectEmail(mailer: YattaMailer)- mailer
- instance running in `"memory"` mode.
Returns Matcher object with assertion methods.
expectEmail(mailer) .toSentCount(1) .to("user@example.com") .withSubject("Welcome") .containing("Verify account");htmlToText
functionIntelligent HTML-to-Plain-Text converter.
htmlToText(html: string): string- html
- HTML source content.
Returns Clean plain text representation with preserved formatting structure.
const text = htmlToText("<h1>Notice</h1><p>Visit <a href='https://foo.bar'>here</a>.</p>");// "=== Notice ===\n\nVisit here (https://foo.bar)."interpolate
functionInterpolates variables into a template string supporting pipes and escaping.
Syntax: - `{{ expression | helper:arg }}`: HTML-escapes output to prevent XSS. - `{{{ rawHtml }}}`: Preserves raw unescaped HTML.
interpolate(templateStr: string, data: Record<string, unknown>, helpers?: Record<string, TemplateHelper>): string- templateStr
- Raw template string.
- data
- Variables object.
- helpers
- Registered template helpers dictionary.
Returns Interpolated and formatted output string.
const out = interpolate( "Hello {{ user.name | uppercase }}, your bill is {{ total | currency:EUR }}", { user: { name: "alice" }, total: 42.5 });// "Hello ALICE, your bill is €42.50"markdownToHtml
functionXSS-Safe Markdown-to-HTML parser designed for email client compatibility.
Features: - Code blocks (triple backticks) with styled `<pre><code>` containers. - Headings (`#`, `##`, `###`) with responsive inline styling. - Blockquotes (`> text`) with styled margins and borders. - Inline formatting (`**bold**`, `*italic*`, `` `code` ``). - Sanitized hyperlinks (`[label](url)`). - Automatic paragraph formatting and line-breaks.
markdownToHtml(md: string): string- md
- Markdown source string.
Returns Sanitized inline HTML string suitable for email rendering.
const html = markdownToHtml("# Welcome\n\nVisit [our site](https://example.com)!");sanitizeUrl
functionValidates and sanitizes a URL string, restricting allowed protocols to safe schemes
sanitizeUrl(url: string): string- url
- Candidate URL string.
Returns Safe URL href if valid, or a safe fallback anchor (`"#unsafe-url"` or `"#invalid-url"`).
sanitizeUrl("https://example.com/confirm"); // "https://example.com/confirm"sanitizeUrl("javascript:alert(1)"); // "#unsafe-url"validateEmailAddress
functionValidates that an email address is syntactically well-formed according to RFC 5322 standards
validateEmailAddress(address: EmailAddress): void- address
- Email address string or `{ name, address }` object.
validateEmailAddress("user@example.com");validateEmailAddress({ name: "Alice", address: "alice@example.com" });MailBuilder
classFluent email message builder DSL providing a clean, chainable API for composing and dispatching emails.
class MailBuilderawait mailer.compose() .to("alice@example.com") .subject("Welcome to Yatta!") .markdown("# Welcome\n\nThanks for signing up!") .send();42 members
fromfrom(address: EmailAddress): thisSets the sender address for this message.
- address
- Sender email or `{ name, address }` object.
Returns Current builder for chaining.
toto(...recipients: RecipientInput[]): thisAppends primary recipient(s) to the email.
- recipients
- One or more email addresses or address arrays.
Returns Current builder for chaining.
andToandTo(...recipients: RecipientInput[]): thisFluent alias for to append primary recipients.
- recipients
- Recipient email addresses.
Returns Current builder for chaining.
cccc(...recipients: RecipientInput[]): thisAppends carbon copy (CC) recipient(s).
- recipients
- CC recipient email addresses.
Returns Current builder for chaining.
andCcandCc(...recipients: RecipientInput[]): thisFluent alias for to append CC recipients.
- recipients
- CC recipient email addresses.
Returns Current builder for chaining.
bccbcc(...recipients: RecipientInput[]): thisAppends blind carbon copy (BCC) recipient(s).
- recipients
- BCC recipient email addresses.
Returns Current builder for chaining.
andBccandBcc(...recipients: RecipientInput[]): thisFluent alias for to append BCC recipients.
- recipients
- BCC recipient email addresses.
Returns Current builder for chaining.
replyToreplyTo(address: EmailAddress): thisSets the Reply-To address header.
- address
- Reply-To email address.
Returns Current builder for chaining.
subjectsubject(subject: string): thisSets the email subject line with CRLF injection validation.
- subject
- Subject line text.
Returns Current builder for chaining.
withSubjectwithSubject(subject: string): thisFluent alias for .
- subject
- Subject line text.
Returns Current builder for chaining.
overrideSubjectoverrideSubject(subject: string): thisExplicit override for the email subject line (e.g. replacing a template default subject).
- subject
- New subject line text.
Returns Current builder for chaining.
texttext(text: string): thisSets the plain text body content.
- text
- Plain text content.
Returns Current builder for chaining.
withTextwithText(text: string): thisFluent alias for .
- text
- Plain text content.
Returns Current builder for chaining.
overrideTextoverrideText(text: string): thisExplicit override for plain text content.
- text
- Plain text content.
Returns Current builder for chaining.
htmlhtml(html: string): thisSets raw or pre-rendered HTML body content.
- html
- HTML source string.
Returns Current builder for chaining.
withHtmlwithHtml(html: string): thisFluent alias for .
- html
- HTML source string.
Returns Current builder for chaining.
overrideHtmloverrideHtml(html: string): thisExplicit override for HTML body content.
- html
- HTML source string.
Returns Current builder for chaining.
markdownmarkdown(md: string): thisConverts Markdown text to XSS-safe HTML and generates plain-text fallback automatically.
- md
- Markdown source content.
Returns Current builder for chaining.
tsts builder.markdown("# Weekly Digest\n\nHere are this week's updates...");withMarkdownwithMarkdown(md: string): thisFluent alias for .
- md
- Markdown source content.
Returns Current builder for chaining.
layoutlayout(name: string): thisSpecifies a registered layout template name to wrap around the rendered HTML body.
- name
- Name of registered layout.
Returns Current builder for chaining.
templatetemplate<K extends keyof TTemplates>(name: K, data: TTemplates[K]): thisConfigures a registered template and its type-safe parameters to render for this email.
- name
- Registered template key.
- data
- Typed parameter object matching template signature.
Returns Current builder for chaining.
tsts builder.template("welcome", { name: "Alice", verifyUrl: "https://..." });withTemplatewithTemplate<K extends keyof TTemplates>(name: K, data: TTemplates[K]): thisFluent alias for .
- name
- Registered template key.
- data
- Typed parameter object.
Returns Current builder for chaining.
untypedTemplateuntypedTemplate(name: string, data: Record<string, unknown>): thisSelects an email template by name with untyped arbitrary dictionary data.
- name
- Template name string.
- data
- Untyped parameters object.
Returns Current builder for chaining.
attachattach(attachment: MailerAttachment): thisAttaches a file or buffer to the message with size and format verification.
- attachment
- Attachment descriptor.
Returns Current builder for chaining.
tsts builder.attach({ filename: "report.pdf", content: pdfBuffer, contentType: "application/pdf"});withAttachmentwithAttachment(attachment: MailerAttachment): thisFluent alias for .
- attachment
- Attachment descriptor.
Returns Current builder for chaining.
withAttachmentswithAttachments(attachments: MailerAttachment[]): thisAttaches an array of files or buffers to the email.
- attachments
- Array of attachment descriptors.
Returns Current builder for chaining.
prioritypriority(level: MailPriority): thisSets the delivery urgency priority (`"high"`, `"normal"`, `"low"`).
- level
- Urgency level.
Returns Current builder for chaining.
idempotencyKeyidempotencyKey(key: string): thisSets a deduplication idempotency key to prevent accidental duplicate dispatches.
- key
- Unique idempotency token (e.g. invoice ID or order UUID).
Returns Current builder for chaining.
headerheader(name: string, value: string): thisSets a custom MIME header name and value with CRLF injection validation.
- name
- Header name (e.g. `"X-Campaign-ID"`).
- value
- Header value.
Returns Current builder for chaining.
withHeaderwithHeader(name: string, value: string): thisFluent alias for .
- name
- Header name.
- value
- Header value.
Returns Current builder for chaining.
inReplyToinReplyTo(messageId: string): thisSets the `In-Reply-To` header for threading replies to a specific previous email message ID.
- messageId
- Previous email Message-ID header value.
Returns Current builder for chaining.
referencesreferences(...messageIds: string[]): thisSets the `References` header for email conversation thread preservation.
- messageIds
- Sequence of prior Message-IDs.
Returns Current builder for chaining.
messageIdmessageId(id: string): thisSets an explicit custom `Message-ID` header.
- id
- Message ID string (e.g. `"<custom-uuid@domain.com>"`).
Returns Current builder for chaining.
unsubscribeunsubscribe(options: { url: string; email?: string; }): thisConfigures RFC 8058 One-Click Unsubscribe headers (`List-Unsubscribe` and `List-Unsubscribe-Post`).
- options
- Unsubscribe targets supporting URL endpoint and/or mailto recipient.
Returns Current builder for chaining.
tsts builder.unsubscribe({ url: "https://example.com/unsubscribe?token=xyz", email: "unsub@example.com"});addRecipientsaddRecipients(target: EmailAddress[], inputs: RecipientInput[]): thisbuildbuild(): SendMailOptionsCompiles the email into standard SendMailOptions without dispatching.
Returns Compiled Nodemailer `SendMailOptions`.
compilecompile(): SendMailOptionsCompiles the email into standard SendMailOptions without dispatching. Alias for .
sendsend(): Promise<SendResult>Compiles and dispatches the email via the host mailer's configured transport.
Returns Send result promise containing message ID and delivery status.
deliverdeliver(): Promise<SendResult>Fluent alias for .
previewpreview(): Promise<{ subject: string; html: string; text: string; from: EmailAddress; to: EmailAddress | EmailAddress[]; previewUrl?: string | false; }>Preview compilation data without sending.
Returns Compiled email preview details, including test preview URL when using `"ethereal"` mode.
sendAsyncsendAsync(): Promise<void>Dispatches asynchronously in the background and tracks execution within the host mailer instance.
deferdefer(): voidFire-and-forget background delivery with automated error logging.
YattaMailer
classHardened email dispatch engine featuring CRLF sanitization, XSS-safe Markdown parsing,
class YattaMailerconst mailer = createMailer({ mode: "smtp", host: "smtp.example.com", auth: { user: "smtp_user", pass: "smtp_pass" }, defaultFrom: "No-Reply <noreply@example.com>"}); await mailer.to("user@example.com") .subject("Welcome") .markdown("Hello **User**!") .send();49 members
transporterPromisepropertytransporterPromise: Promise<Transporter> | nulltemplatespropertytemplates:layoutspropertylayouts:helpersStorepropertyhelpersStore:sentMemoryStoragepropertysentMemoryStorage: SentMemoryEmail[]backgroundPromisespropertybackgroundPromises:rateLimitTokenspropertyrateLimitTokens: numberlastRateLimitRefillpropertylastRateLimitRefill: numberactiveConcurrentJobspropertyactiveConcurrentJobs: numberconcurrencyWaiterspropertyconcurrencyWaiters: Array<() => void>defaultFrompropertydefaultFrom?: EmailAddressDefault sender email address used when `.from()` is omitted.
retriespropertyretries: numberMaximum retry attempts for transient delivery failures.
modepropertymode: "smtp" | "ethereal" | "terminal" | "memory"Active delivery mode (`"smtp"`, `"ethereal"`, `"terminal"`, `"memory"`).
dryRunpropertydryRun: booleanWhether dryRun mode is enabled (compiles and logs without sending).
maxAttachmentSizepropertymaxAttachmentSize: numberMaximum allowable attachment byte size in bytes.
maxAttachmentspropertymaxAttachments: numberMaximum number of attachments permitted per message.
loggerpropertylogger: MailLoggerStructured logger instance.
hookspropertyhooks?: MailHooksLifecycle hook callbacks.
optionspropertyoptions: MailerOptions<TTemplates>User-supplied configuration options.
metricspropertymetrics: MailStatsOperational metrics and delivery counters.
helpersgetterhelpers: Record<string, TemplateHelper>Retrieves an object map of all registered template helper pipe functions.
registerHelperregisterHelper(name: string, helper: TemplateHelper): thisRegisters a custom helper function for template interpolation pipes (e.g. `{{ value | customHelper:arg }}`).
- name
- Unique helper filter name.
- helper
- Transformation function.
Returns Current mailer for chaining.
tsts mailer.registerHelper("discount", (price, percent) => { return `$${(Number(price) * (1 - Number(percent) / 100)).toFixed(2)}`;});registerLayoutregisterLayout(name: string, htmlTemplate: string): thisRegisters a reusable HTML layout template wrapper.
- name
- Layout identifier name.
- htmlTemplate
- HTML layout wrapper template string.
Returns Current mailer for chaining.
tsts mailer.registerLayout("main", ` <html><body><header>Logo</header><main>{{{ body }}}</main><footer>Footer</footer></body></html>`);getLayoutgetLayout(name: string): string | undefinedRetrieves a registered HTML layout template string by name.
- name
- Layout identifier name.
Returns Layout template string if found.
registerTemplateregisterTemplate<TData extends Record<string, unknown> = Record<string, unknown>>(name: string, renderer: TemplateRenderer<TData>): thisRegisters an email template renderer.
- name
- Template name identifier.
- renderer
- Template definition object or callback function.
Returns Current mailer for chaining.
tsts mailer.registerTemplate("welcome", { subject: "Welcome, {{ name }}!", html: "<h1>Welcome</h1><p>Click <a href='{{ verifyUrl }}'>here</a> to verify.</p>", layout: "main"});getTemplategetTemplate(name: string): TemplateRenderer<any> | undefinedRetrieves a registered email template renderer by name.
- name
- Template name identifier.
Returns Template renderer if found.
validateTemplatesvalidateTemplates(): { valid: boolean; errors: string[]; }Validates that all registered templates reference existing registered layout templates.
Returns Validation result containing validity flag and error messages.
validateAttachmentvalidateAttachment(att: MailerAttachment): voidValidates that an attachment specifies a valid source and does not exceed `maxAttachmentSize`.
- att
- Attachment descriptor.
composecompose(): MailBuilder<TTemplates>Creates a new fluent instance bound to this mailer.
Returns Fluent mail builder DSL.
toto(...recipients: RecipientInput[]): MailBuilder<TTemplates>Convenience entry point creating a with predefined recipient(s).
- recipients
- Recipient email address(es).
Returns Fluent mail builder DSL.
sendsend(options: DirectSendOptions<TTemplates>): Promise<SendResult>Direct email delivery without using the fluent builder.
- options
- Direct delivery parameters.
Returns Send result promise with message ID and delivery status.
tsts await mailer.send({ to: "user@example.com", subject: "Order Confirmation", html: "<h1>Order Received!</h1>"});batchbatch(items: Array<DirectSendOptions<TTemplates> | MailBuilder<TTemplates>>): Promise<{ results: SendResult[]; total: number; failed: number; }>Batch sending utility.
- items
- Array of direct send option objects or pre-configured `MailBuilder` instances.
Returns Aggregate summary containing results array, total count, and failed count.
tsts const summary = await mailer.batch([ { to: "alice@example.com", subject: "Hi Alice", text: "..." }, { to: "bob@example.com", subject: "Hi Bob", text: "..." },]);console.log(`Dispatched ${summary.total - summary.failed}/${summary.total}`);statsstats(): MailStatsReturns a snapshot copy of current operational metrics and delivery statistics.
sentsent(): readonly SentMemoryEmail[]In `"memory"` test mode, returns a read-only list of all captured sent email records.
lastSentlastSent(): SentMemoryEmail | undefinedIn `"memory"` test mode, returns the most recently sent email record, or `undefined` if none.
sentCountsentCount(): numberIn `"memory"` test mode, returns the count of sent emails recorded so far.
findSentfindSent(predicate: (email: SentMemoryEmail) => boolean): SentMemoryEmail[]In `"memory"` test mode, filters recorded emails by a predicate callback.
- predicate
- Filter predicate.
Returns Matching sent email records.
clearSentclearSent(): voidIn `"memory"` test mode, clears the recorded list of sent emails.
resetreset(): voidIn `"memory"` test mode, clears all recorded sent emails and resets operational metrics to zero.
getTransportergetTransporter(): Promise<Transporter>verifyverify(): Promise<boolean>Verifies the SMTP transport connection configuration and credentials.
Returns `true` if transport verification succeeds.
dispatchdispatch(mailOptions: SendMailOptions): Promise<SendResult>Core dispatch pipeline. Compiles, rate-limits, retries, and sends raw Nodemailer options.
- mailOptions
- Compiled Nodemailer options.
Returns Delivery result promise.
acquireRateLimitAndConcurrencyacquireRateLimitAndConcurrency(): Promise<void>releaseConcurrencyreleaseConcurrency(): voidtrackBackgroundDeliverytrackBackgroundDelivery(mailOptions: SendMailOptions): voidTracks an asynchronous background delivery task within the mailer instance.
- mailOptions
- Nodemailer send options.
draindrain(): Promise<void>Waits for all in-flight background deliveries to finish before process termination.
isTransientErrorisTransientError(err: unknown): booleancloseclose(): Promise<void>Closes active transport connections and drains background tasks.
[Symbol.asyncDispose][Symbol.asyncDispose]()Async disposable resource cleanup hook (`using mailer = ...`).
YattaMailError
classBase exception thrown by the Yatta Mail engine during validation, rendering, or dispatch errors.
class YattaMailError extends Errortry { await mailer.send({ to: "invalid-email", subject: "Hello" });} catch (error) { if (error instanceof YattaMailError) { console.error("Mail error:", error.message, error.details); }}Types
DirectSendOptions
interfaceDirect options passed to for one-shot delivery without fluent builder.
interface DirectSendOptions<TTemplates extends Record<string, Record<string, unknown>> = RegisteredTemplates, K extends keyof TTemplates = keyof TTemplates>16 members
frompropertyfrom?: EmailAddressSender address override.
topropertyto: RecipientInputPrimary recipient(s).
ccpropertycc?: RecipientInputCarbon copy (CC) recipient(s).
bccpropertybcc?: RecipientInputBlind carbon copy (BCC) recipient(s).
replyTopropertyreplyTo?: EmailAddressReply-To email address.
subjectpropertysubject?: stringEmail subject line.
textpropertytext?: stringPlain text email body.
htmlpropertyhtml?: stringHTML email body.
markdownpropertymarkdown?: stringMarkdown text converted to HTML with automated plain-text fallback.
templatepropertytemplate?: KName of registered template to render.
datapropertydata?: TTemplates[K]Data variables passed to template renderer.
layoutpropertylayout?: stringLayout template name wrapping the rendered HTML content.
attachmentspropertyattachments?: MailerAttachment[]Attachments list.
headerspropertyheaders?: Record<string, string>Custom MIME headers (e.g. `X-Custom-Header`).
prioritypropertypriority?: MailPriorityDelivery priority.
idempotencyKeypropertyidempotencyKey?: stringDeduplication key preventing duplicate delivery via `X-Idempotency-Key`.
MailerAttachment
interfaceEmail attachment specification supporting file paths, in-memory buffers/strings, and embedded inline images.
interface MailerAttachment6 members
filenamepropertyfilename?: stringDisplay filename for the attachment (e.g. `"invoice.pdf"`).
contentpropertycontent?: string | Buffer | Uint8ArrayIn-memory content payload as a string, Buffer, or Uint8Array.
pathpropertypath?: stringFilesystem path to stream the attachment from.
contentTypepropertycontentType?: stringExplicit MIME content type (e.g. `"application/pdf"`, `"image/png"`).
cidpropertycid?: stringContent-ID for embedding inline images in HTML templates (`<img src="cid:logo"/>`).
encodingpropertyencoding?: stringContent transfer encoding (e.g. `"base64"`).
MailerOptions
interfaceOptions configuring the instance.
interface MailerOptions<TTemplates extends Record<string, any> = RegisteredTemplates>16 members
providerpropertyprovider?: MailProviderPreset provider: `"gmail" | "resend" | "postmark" | "sendgrid" | "mailgun" | "brevo" | "ses"`.
hostpropertyhost?: stringSMTP Host (defaults to `process.env.YATTA_MAIL_HOST` or `SMTP_HOST`).
portpropertyport?: numberSMTP Port (defaults to `process.env.YATTA_MAIL_PORT` or `SMTP_PORT` or `587`).
securepropertysecure?: booleanUse TLS/SSL (defaults to true if port is 465).
authpropertyauth?: { user: string; pass: string; }SMTP Authentication credentials.
defaultFrompropertydefaultFrom?: EmailAddressDefault sender address applied when `.from()` is omitted.
modepropertymode?: "smtp" | "ethereal" | "terminal" | "memory"Delivery mode: `"smtp"` (live network), `"ethereal"` (test inbox preview), `"terminal"` (console log), `"memory"` (unit tests).
retriespropertyretries?: numberMaximum retry attempts for transient delivery failures (0-10, default: 3).
dryRunpropertydryRun?: booleanWhen enabled, messages are compiled, logged, and validated without sending over network.
templatespropertytemplates?: Record<string, TemplateRenderer<any>>In-line templates definition for direct type inference.
layoutspropertylayouts?: Record<string, string>In-line layouts definition.
maxAttachmentSizepropertymaxAttachmentSize?: numberMaximum allowable attachment byte size (default: 10MB).
maxAttachmentspropertymaxAttachments?: numberMaximum count of attachments per email (default: 10).
rateLimitpropertyrateLimit?: MailRateLimitOptionsBuilt-in rate limiting and concurrency options.
loggerpropertylogger?: MailLoggerCustom structured logger instance.
hookspropertyhooks?: MailHooksLifecycle hooks for intercepting email dispatch events.
MailHooks
interfaceLifecycle hook callbacks executed at various stages of email compilation, transmission, and error handling.
interface MailHooks5 members
onQueuedpropertyonQueued?: (mail: SendMailOptions) => void | Promise<void>Invoked when an email is enqueued for background dispatch via `.sendAsync()` or `.defer()`.
beforeSendpropertybeforeSend?: (mail: SendMailOptions) => void | Promise<void>Invoked immediately prior to attempting network transmission.
afterSendpropertyafterSend?: (result: SendResult, mail: SendMailOptions) => void | Promise<void>Invoked after an email has been successfully accepted by the transport.
onErrorpropertyonError?: (error: Error, mail: SendMailOptions) => void | Promise<void>Invoked when delivery permanently fails after exhausting all retries.
onRetrypropertyonRetry?: (attempt: number, error: Error, delayMs: number) => voidInvoked when a transient delivery error triggers a retry attempt with backoff delay.
MailLogger
interfaceStructured logger interface for mail delivery operations and debugging.
interface MailLogger4 members
debugdebug(...args: unknown[]): voidLog diagnostic or low-level trace messages.
infoinfo(...args: unknown[]): voidLog informational delivery notices.
warnwarn(...args: unknown[]): voidLog operational warnings.
errorerror(...args: unknown[]): voidLog delivery and runtime errors.
MailProxyFunction
interfaceCallable function signature for the global proxy facade.
interface MailProxyFunction15 members
toto<TTemplates extends Record<string, Record<string, unknown>> = RegisteredTemplates>(...recipients: RecipientInput[]): MailBuilder<TTemplates>Compose an email targeting one or more recipients using default mailer.
composecompose<TTemplates extends Record<string, Record<string, unknown>> = RegisteredTemplates>(): MailBuilder<TTemplates>Create a fluent builder session using default mailer.
sendsend(options: DirectSendOptions): Promise<SendResult>Directly dispatch an email using default mailer.
batchbatch(items: Array<DirectSendOptions | MailBuilder<any>>): Promise<{ results: SendResult[]; total: number; failed: number; }>Concurrently send multiple emails using default mailer.
verifyverify(): Promise<boolean>Verify default transport connection.
closeclose(): Promise<void>Close default transport connections.
draindrain(): Promise<void>Drain in-flight background deliveries on default mailer.
sentsent(): readonly SentMemoryEmail[]In memory mode, retrieve sent emails on default mailer.
lastSentlastSent(): SentMemoryEmail | undefinedIn memory mode, retrieve most recent email on default mailer.
sentCountsentCount(): numberIn memory mode, retrieve sent count on default mailer.
findSentfindSent(predicate: (email: SentMemoryEmail) => boolean): SentMemoryEmail[]In memory mode, find sent emails matching predicate on default mailer.
clearSentclearSent(): voidIn memory mode, clear sent emails on default mailer.
resetreset(): voidIn memory mode, reset sent emails and metrics on default mailer.
statsstats(): MailStatsGet metrics stats from default mailer.
[call]call(): YattaMailer<TTemplates>Access the default configured instance.
MailRateLimitOptions
interfaceRate limiting and concurrency controls for outbound email dispatch.
interface MailRateLimitOptions3 members
maxpropertymax?: numberMaximum messages allowed within the time window (default: unlimited).
windowMspropertywindowMs?: numberRolling time window in milliseconds for token refill (default: `1000` ms).
maxConcurrencypropertymaxConcurrency?: numberMaximum concurrent SMTP deliveries allowed simultaneously (default: `5`).
MailRegister
interfaceGlobal interface mergeable by application code for template type safety.
interface MailRegisterdeclare module "../types/mail" { interface MailRegister { templates: { welcome: { name: string; verifyUrl: string }; resetPassword: { email: string; token: string; expiresMinutes: number }; }; }}MailStats
interfaceAggregated operational metrics and delivery statistics tracked by .
interface MailStats8 members
sentpropertysent: numberTotal count of successfully accepted email dispatches.
failedpropertyfailed: numberTotal count of failed deliveries that exhausted all retries.
rejectedpropertyrejected: numberTotal count of recipients explicitly rejected by SMTP relays.
retriespropertyretries: numberTotal count of retry attempts executed due to transient delivery errors.
queuedpropertyqueued: numberTotal count of background asynchronous deliveries queued.
dryRunpropertydryRun: numberTotal count of emails processed in dryRun mode without network transmission.
totalDeliveryTimeMspropertytotalDeliveryTimeMs: numberCumulative milliseconds spent in SMTP network transmission.
averageDeliveryTimeMspropertyaverageDeliveryTimeMs: numberAverage milliseconds spent per successful email delivery.
SendResult
interfaceResult returned upon sending or previewing an email.
interface SendResult6 members
messageIdpropertymessageId: stringUnique message identifier assigned by transport or SMTP relay.
acceptedpropertyaccepted: string[]List of recipient addresses accepted by the relay.
rejectedpropertyrejected: string[]List of recipient addresses rejected by the relay.
failedpropertyfailed: booleanWhether the delivery encountered rejection or failures.
previewUrlpropertypreviewUrl?: string | falseWeb URL for previewing test emails in `"ethereal"` development mode.
rawpropertyraw?: unknownRaw response object returned by underlying Nodemailer transport.
SentMemoryEmail
interfaceRecord of an email captured in-memory during tests in `"memory"` mode.
interface SentMemoryEmail2 members
optionspropertyoptions: SendMailOptionsNodemailer send options compiled for this email.
sentAtpropertysentAt: DateTimestamp when the email was recorded in memory.
TemplateRenderResult
interfaceOutput components produced by compiling or rendering an email template.
interface TemplateRenderResult3 members
subjectpropertysubject?: stringOptional subject line generated by the template.
htmlpropertyhtml: stringCompiled HTML email body.
textpropertytext?: stringOptional plain-text fallback content. Generated automatically if omitted.
EmailAddress
typeRepresents an email recipient or sender, either as a plain address string or an object with display name.
type EmailAddress = string | { name?: string; address: string; }MailPriority
typeEmail urgency level controlling client presentation and priority headers.
type MailPriority = "high" | "normal" | "low"MailProvider
typeSupported built-in email provider presets.
type MailProvider = "smtp" | "gmail" | "resend" | "postmark" | "sendgrid" | "mailgun" | "brevo" | "ses"MailProxy
typeUnion proxy type combining and .
type MailProxy = MailProxyFunction & YattaMailerPrettify
typeUtility type expanding nested object properties for clearer IDE IntelliSense previews.
type Prettify<T> = { [K in keyof T]: T[K]; } & {}RecipientInput
typeA single recipient address or an array of recipient addresses.
type RecipientInput = EmailAddress | readonly EmailAddress[]RegisteredTemplates
typeExtracts registered template data contracts from , or falls back to any object map.
type RegisteredTemplates = MailRegister extends { templates: infer T extends Record<string, Record<string, unknown>>; } ? T : Record<string, Record<string, unknown>>TemplateHelper
typeTransformation function for template interpolation pipes (e.g. `{{ amount | currency:USD }}`).
type TemplateHelper = (value: unknown, arg?: string) => string- value
- Input value from data object.
- arg
- Optional argument passed after the colon in the pipe definition.
Returns Formatted output string.
TemplateRenderer
typeDefinition of an email template renderer.
Supports three formats: 1. Static object with template strings: `{ subject?, html, text?, layout? }` 2. Object with `.render(data)` function and optional layout. 3. Functional renderer callback: `(data: TData) => TemplateRenderResult`.
type TemplateRenderer<TData extends Record<string, unknown> = Record<string, unknown>> = { subject?: string; html: string; text?: string; layout?: string; } | { render(data: TData): TemplateRenderResult; layout?: string; } | ((data: TData) => TemplateRenderResult)AuthConfig or JobPayload — declaring your schema once is enough for the rest to follow. See Typed keys.