API reference

yatta/mail

Templates, layouts, transports, and preview sending.

34 exported symbols and 175 members, read from src/types/mail.ts.

Construct

assertEmailSent

function

Convenience 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`).
tsts
assertEmailSent(mailer, { to: "alice@example.com", subject: /Welcome/i });

assertNoCrlf

function

Asserts 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.
tsts
assertNoCrlf("Subject line", "Subject"); // PassesassertNoCrlf("Subject\nBcc: hacker@evil.com", "Subject"); // Throws YattaMailError

createMailer

function

Creates 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.

tsts
export const mailer = createMailer({  provider: "resend",  auth: { user: "resend", pass: process.env.RESEND_API_KEY! },  defaultFrom: "Yatta <noreply@yatta.dev>"});

escapeHtml

function

Escapes 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

function

Fluent 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.

tsts
expectEmail(mailer)  .toSentCount(1)  .to("user@example.com")  .withSubject("Welcome")  .containing("Verify account");

htmlToText

function

Intelligent HTML-to-Plain-Text converter.

htmlToText(html: string): string
html
HTML source content.

Returns Clean plain text representation with preserved formatting structure.

tsts
const text = htmlToText("<h1>Notice</h1><p>Visit <a href='https://foo.bar'>here</a>.</p>");// "=== Notice ===\n\nVisit here (https://foo.bar)."

interpolate

function

Interpolates 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.

tsts
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

function

XSS-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.

tsts
const html = markdownToHtml("# Welcome\n\nVisit [our site](https://example.com)!");

sanitizeUrl

function

Validates 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"`).

tsts
sanitizeUrl("https://example.com/confirm"); // "https://example.com/confirm"sanitizeUrl("javascript:alert(1)"); // "#unsafe-url"

validateEmailAddress

function

Validates 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.
tsts
validateEmailAddress("user@example.com");validateEmailAddress({ name: "Alice", address: "alice@example.com" });

MailBuilder

class

Fluent email message builder DSL providing a clean, chainable API for composing and dispatching emails.

tsts
await mailer.compose()  .to("alice@example.com")  .subject("Welcome to Yatta!")  .markdown("# Welcome\n\nThanks for signing up!")  .send();

42 members

  • from
    from(address: EmailAddress): this

    Sets the sender address for this message.

    address
    Sender email or `{ name, address }` object.

    Returns Current builder for chaining.

  • to
    to(...recipients: RecipientInput[]): this

    Appends primary recipient(s) to the email.

    recipients
    One or more email addresses or address arrays.

    Returns Current builder for chaining.

  • andTo
    andTo(...recipients: RecipientInput[]): this

    Fluent alias for to append primary recipients.

    recipients
    Recipient email addresses.

    Returns Current builder for chaining.

  • cc
    cc(...recipients: RecipientInput[]): this

    Appends carbon copy (CC) recipient(s).

    recipients
    CC recipient email addresses.

    Returns Current builder for chaining.

  • andCc
    andCc(...recipients: RecipientInput[]): this

    Fluent alias for to append CC recipients.

    recipients
    CC recipient email addresses.

    Returns Current builder for chaining.

  • bcc
    bcc(...recipients: RecipientInput[]): this

    Appends blind carbon copy (BCC) recipient(s).

    recipients
    BCC recipient email addresses.

    Returns Current builder for chaining.

  • andBcc
    andBcc(...recipients: RecipientInput[]): this

    Fluent alias for to append BCC recipients.

    recipients
    BCC recipient email addresses.

    Returns Current builder for chaining.

  • replyTo
    replyTo(address: EmailAddress): this

    Sets the Reply-To address header.

    address
    Reply-To email address.

    Returns Current builder for chaining.

  • subject
    subject(subject: string): this

    Sets the email subject line with CRLF injection validation.

    subject
    Subject line text.

    Returns Current builder for chaining.

  • withSubject
    withSubject(subject: string): this

    Fluent alias for .

    subject
    Subject line text.

    Returns Current builder for chaining.

  • overrideSubject
    overrideSubject(subject: string): this

    Explicit override for the email subject line (e.g. replacing a template default subject).

    subject
    New subject line text.

    Returns Current builder for chaining.

  • text
    text(text: string): this

    Sets the plain text body content.

    text
    Plain text content.

    Returns Current builder for chaining.

  • withText
    withText(text: string): this

    Fluent alias for .

    text
    Plain text content.

    Returns Current builder for chaining.

  • overrideText
    overrideText(text: string): this

    Explicit override for plain text content.

    text
    Plain text content.

    Returns Current builder for chaining.

  • html
    html(html: string): this

    Sets raw or pre-rendered HTML body content.

    html
    HTML source string.

    Returns Current builder for chaining.

  • withHtml
    withHtml(html: string): this

    Fluent alias for .

    html
    HTML source string.

    Returns Current builder for chaining.

  • overrideHtml
    overrideHtml(html: string): this

    Explicit override for HTML body content.

    html
    HTML source string.

    Returns Current builder for chaining.

  • markdown
    markdown(md: string): this

    Converts 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...");
  • withMarkdown
    withMarkdown(md: string): this

    Fluent alias for .

    md
    Markdown source content.

    Returns Current builder for chaining.

  • layout
    layout(name: string): this

    Specifies a registered layout template name to wrap around the rendered HTML body.

    name
    Name of registered layout.

    Returns Current builder for chaining.

  • template
    template<K extends keyof TTemplates>(name: K, data: TTemplates[K]): this

    Configures 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://..." });
  • withTemplate
    withTemplate<K extends keyof TTemplates>(name: K, data: TTemplates[K]): this

    Fluent alias for .

    name
    Registered template key.
    data
    Typed parameter object.

    Returns Current builder for chaining.

  • untypedTemplate
    untypedTemplate(name: string, data: Record<string, unknown>): this

    Selects an email template by name with untyped arbitrary dictionary data.

    name
    Template name string.
    data
    Untyped parameters object.

    Returns Current builder for chaining.

  • attach
    attach(attachment: MailerAttachment): this

    Attaches 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"});
  • withAttachment
    withAttachment(attachment: MailerAttachment): this

    Fluent alias for .

    attachment
    Attachment descriptor.

    Returns Current builder for chaining.

  • withAttachments
    withAttachments(attachments: MailerAttachment[]): this

    Attaches an array of files or buffers to the email.

    attachments
    Array of attachment descriptors.

    Returns Current builder for chaining.

  • priority
    priority(level: MailPriority): this

    Sets the delivery urgency priority (`"high"`, `"normal"`, `"low"`).

    level
    Urgency level.

    Returns Current builder for chaining.

  • idempotencyKey
    idempotencyKey(key: string): this

    Sets 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.

  • header
    header(name: string, value: string): this

    Sets 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.

  • withHeader
    withHeader(name: string, value: string): this

    Fluent alias for .

    name
    Header name.
    value
    Header value.

    Returns Current builder for chaining.

  • inReplyTo
    inReplyTo(messageId: string): this

    Sets 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.

  • references
    references(...messageIds: string[]): this

    Sets the `References` header for email conversation thread preservation.

    messageIds
    Sequence of prior Message-IDs.

    Returns Current builder for chaining.

  • messageId
    messageId(id: string): this

    Sets an explicit custom `Message-ID` header.

    id
    Message ID string (e.g. `"<custom-uuid@domain.com>"`).

    Returns Current builder for chaining.

  • unsubscribe
    unsubscribe(options: { url: string; email?: string; }): this

    Configures 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"});
  • addRecipients
    addRecipients(target: EmailAddress[], inputs: RecipientInput[]): this
  • build
    build(): SendMailOptions

    Compiles the email into standard SendMailOptions without dispatching.

    Returns Compiled Nodemailer `SendMailOptions`.

  • compile
    compile(): SendMailOptions

    Compiles the email into standard SendMailOptions without dispatching. Alias for .

  • send
    send(): Promise<SendResult>

    Compiles and dispatches the email via the host mailer's configured transport.

    Returns Send result promise containing message ID and delivery status.

  • deliver
    deliver(): Promise<SendResult>

    Fluent alias for .

  • preview
    preview(): 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.

  • sendAsync
    sendAsync(): Promise<void>

    Dispatches asynchronously in the background and tracks execution within the host mailer instance.

  • defer
    defer(): void

    Fire-and-forget background delivery with automated error logging.

YattaMailer

class

Hardened email dispatch engine featuring CRLF sanitization, XSS-safe Markdown parsing,

tsts
const 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

  • transporterPromiseproperty
    transporterPromise: Promise<Transporter> | null
  • templatesproperty
    templates:
  • layoutsproperty
    layouts:
  • helpersStoreproperty
    helpersStore:
  • sentMemoryStorageproperty
    sentMemoryStorage: SentMemoryEmail[]
  • backgroundPromisesproperty
    backgroundPromises:
  • rateLimitTokensproperty
    rateLimitTokens: number
  • lastRateLimitRefillproperty
    lastRateLimitRefill: number
  • activeConcurrentJobsproperty
    activeConcurrentJobs: number
  • concurrencyWaitersproperty
    concurrencyWaiters: Array<() => void>
  • defaultFromproperty
    defaultFrom?: EmailAddress

    Default sender email address used when `.from()` is omitted.

  • retriesproperty
    retries: number

    Maximum retry attempts for transient delivery failures.

  • modeproperty
    mode: "smtp" | "ethereal" | "terminal" | "memory"

    Active delivery mode (`"smtp"`, `"ethereal"`, `"terminal"`, `"memory"`).

  • dryRunproperty
    dryRun: boolean

    Whether dryRun mode is enabled (compiles and logs without sending).

  • maxAttachmentSizeproperty
    maxAttachmentSize: number

    Maximum allowable attachment byte size in bytes.

  • maxAttachmentsproperty
    maxAttachments: number

    Maximum number of attachments permitted per message.

  • loggerproperty
    logger: MailLogger

    Structured logger instance.

  • hooksproperty
    hooks?: MailHooks

    Lifecycle hook callbacks.

  • optionsproperty
    options: MailerOptions<TTemplates>

    User-supplied configuration options.

  • metricsproperty
    metrics: MailStats

    Operational metrics and delivery counters.

  • helpersgetter
    helpers: Record<string, TemplateHelper>

    Retrieves an object map of all registered template helper pipe functions.

  • registerHelper
    registerHelper(name: string, helper: TemplateHelper): this

    Registers 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)}`;});
  • registerLayout
    registerLayout(name: string, htmlTemplate: string): this

    Registers 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>`);
  • getLayout
    getLayout(name: string): string | undefined

    Retrieves a registered HTML layout template string by name.

    name
    Layout identifier name.

    Returns Layout template string if found.

  • registerTemplate
    registerTemplate<TData extends Record<string, unknown> = Record<string, unknown>>(name: string, renderer: TemplateRenderer<TData>): this

    Registers 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"});
  • getTemplate
    getTemplate(name: string): TemplateRenderer<any> | undefined

    Retrieves a registered email template renderer by name.

    name
    Template name identifier.

    Returns Template renderer if found.

  • validateTemplates
    validateTemplates(): { valid: boolean; errors: string[]; }

    Validates that all registered templates reference existing registered layout templates.

    Returns Validation result containing validity flag and error messages.

  • validateAttachment
    validateAttachment(att: MailerAttachment): void

    Validates that an attachment specifies a valid source and does not exceed `maxAttachmentSize`.

    att
    Attachment descriptor.
  • compose
    compose(): MailBuilder<TTemplates>

    Creates a new fluent instance bound to this mailer.

    Returns Fluent mail builder DSL.

  • to
    to(...recipients: RecipientInput[]): MailBuilder<TTemplates>

    Convenience entry point creating a with predefined recipient(s).

    recipients
    Recipient email address(es).

    Returns Fluent mail builder DSL.

  • send
    send(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>"});
  • batch
    batch(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}`);
  • stats
    stats(): MailStats

    Returns a snapshot copy of current operational metrics and delivery statistics.

  • sent
    sent(): readonly SentMemoryEmail[]

    In `"memory"` test mode, returns a read-only list of all captured sent email records.

  • lastSent
    lastSent(): SentMemoryEmail | undefined

    In `"memory"` test mode, returns the most recently sent email record, or `undefined` if none.

  • sentCount
    sentCount(): number

    In `"memory"` test mode, returns the count of sent emails recorded so far.

  • findSent
    findSent(predicate: (email: SentMemoryEmail) => boolean): SentMemoryEmail[]

    In `"memory"` test mode, filters recorded emails by a predicate callback.

    predicate
    Filter predicate.

    Returns Matching sent email records.

  • clearSent
    clearSent(): void

    In `"memory"` test mode, clears the recorded list of sent emails.

  • reset
    reset(): void

    In `"memory"` test mode, clears all recorded sent emails and resets operational metrics to zero.

  • getTransporter
    getTransporter(): Promise<Transporter>
  • verify
    verify(): Promise<boolean>

    Verifies the SMTP transport connection configuration and credentials.

    Returns `true` if transport verification succeeds.

  • dispatch
    dispatch(mailOptions: SendMailOptions): Promise<SendResult>

    Core dispatch pipeline. Compiles, rate-limits, retries, and sends raw Nodemailer options.

    mailOptions
    Compiled Nodemailer options.

    Returns Delivery result promise.

  • acquireRateLimitAndConcurrency
    acquireRateLimitAndConcurrency(): Promise<void>
  • releaseConcurrency
    releaseConcurrency(): void
  • trackBackgroundDelivery
    trackBackgroundDelivery(mailOptions: SendMailOptions): void

    Tracks an asynchronous background delivery task within the mailer instance.

    mailOptions
    Nodemailer send options.
  • drain
    drain(): Promise<void>

    Waits for all in-flight background deliveries to finish before process termination.

  • isTransientError
    isTransientError(err: unknown): boolean
  • close
    close(): Promise<void>

    Closes active transport connections and drains background tasks.

  • [Symbol.asyncDispose]
    [Symbol.asyncDispose]()

    Async disposable resource cleanup hook (`using mailer = ...`).

YattaMailError

class

Base exception thrown by the Yatta Mail engine during validation, rendering, or dispatch errors.

class YattaMailError extends Error
tsts
try {  await mailer.send({ to: "invalid-email", subject: "Hello" });} catch (error) {  if (error instanceof YattaMailError) {    console.error("Mail error:", error.message, error.details);  }}

Types

DirectSendOptions

interface

Direct 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

  • fromproperty
    from?: EmailAddress

    Sender address override.

  • toproperty
    to: RecipientInput

    Primary recipient(s).

  • ccproperty
    cc?: RecipientInput

    Carbon copy (CC) recipient(s).

  • bccproperty
    bcc?: RecipientInput

    Blind carbon copy (BCC) recipient(s).

  • replyToproperty
    replyTo?: EmailAddress

    Reply-To email address.

  • subjectproperty
    subject?: string

    Email subject line.

  • textproperty
    text?: string

    Plain text email body.

  • htmlproperty
    html?: string

    HTML email body.

  • markdownproperty
    markdown?: string

    Markdown text converted to HTML with automated plain-text fallback.

  • templateproperty
    template?: K

    Name of registered template to render.

  • dataproperty
    data?: TTemplates[K]

    Data variables passed to template renderer.

  • layoutproperty
    layout?: string

    Layout template name wrapping the rendered HTML content.

  • attachmentsproperty
    attachments?: MailerAttachment[]

    Attachments list.

  • headersproperty
    headers?: Record<string, string>

    Custom MIME headers (e.g. `X-Custom-Header`).

  • priorityproperty
    priority?: MailPriority

    Delivery priority.

  • idempotencyKeyproperty
    idempotencyKey?: string

    Deduplication key preventing duplicate delivery via `X-Idempotency-Key`.

MailerAttachment

interface

Email attachment specification supporting file paths, in-memory buffers/strings, and embedded inline images.

6 members

  • filenameproperty
    filename?: string

    Display filename for the attachment (e.g. `"invoice.pdf"`).

  • contentproperty
    content?: string | Buffer | Uint8Array

    In-memory content payload as a string, Buffer, or Uint8Array.

  • pathproperty
    path?: string

    Filesystem path to stream the attachment from.

  • contentTypeproperty
    contentType?: string

    Explicit MIME content type (e.g. `"application/pdf"`, `"image/png"`).

  • cidproperty
    cid?: string

    Content-ID for embedding inline images in HTML templates (`<img src="cid:logo"/>`).

  • encodingproperty
    encoding?: string

    Content transfer encoding (e.g. `"base64"`).

MailerOptions

interface

Options configuring the instance.

interface MailerOptions<TTemplates extends Record<string, any> = RegisteredTemplates>

16 members

  • providerproperty
    provider?: MailProvider

    Preset provider: `"gmail" | "resend" | "postmark" | "sendgrid" | "mailgun" | "brevo" | "ses"`.

  • hostproperty
    host?: string

    SMTP Host (defaults to `process.env.YATTA_MAIL_HOST` or `SMTP_HOST`).

  • portproperty
    port?: number

    SMTP Port (defaults to `process.env.YATTA_MAIL_PORT` or `SMTP_PORT` or `587`).

  • secureproperty
    secure?: boolean

    Use TLS/SSL (defaults to true if port is 465).

  • authproperty
    auth?: { user: string; pass: string; }

    SMTP Authentication credentials.

  • defaultFromproperty
    defaultFrom?: EmailAddress

    Default sender address applied when `.from()` is omitted.

  • modeproperty
    mode?: "smtp" | "ethereal" | "terminal" | "memory"

    Delivery mode: `"smtp"` (live network), `"ethereal"` (test inbox preview), `"terminal"` (console log), `"memory"` (unit tests).

  • retriesproperty
    retries?: number

    Maximum retry attempts for transient delivery failures (0-10, default: 3).

  • dryRunproperty
    dryRun?: boolean

    When enabled, messages are compiled, logged, and validated without sending over network.

  • templatesproperty
    templates?: Record<string, TemplateRenderer<any>>

    In-line templates definition for direct type inference.

  • layoutsproperty
    layouts?: Record<string, string>

    In-line layouts definition.

  • maxAttachmentSizeproperty
    maxAttachmentSize?: number

    Maximum allowable attachment byte size (default: 10MB).

  • maxAttachmentsproperty
    maxAttachments?: number

    Maximum count of attachments per email (default: 10).

  • rateLimitproperty
    rateLimit?: MailRateLimitOptions

    Built-in rate limiting and concurrency options.

  • loggerproperty
    logger?: MailLogger

    Custom structured logger instance.

  • hooksproperty
    hooks?: MailHooks

    Lifecycle hooks for intercepting email dispatch events.

MailHooks

interface

Lifecycle hook callbacks executed at various stages of email compilation, transmission, and error handling.

interface MailHooks

5 members

  • onQueuedproperty
    onQueued?: (mail: SendMailOptions) => void | Promise<void>

    Invoked when an email is enqueued for background dispatch via `.sendAsync()` or `.defer()`.

  • beforeSendproperty
    beforeSend?: (mail: SendMailOptions) => void | Promise<void>

    Invoked immediately prior to attempting network transmission.

  • afterSendproperty
    afterSend?: (result: SendResult, mail: SendMailOptions) => void | Promise<void>

    Invoked after an email has been successfully accepted by the transport.

  • onErrorproperty
    onError?: (error: Error, mail: SendMailOptions) => void | Promise<void>

    Invoked when delivery permanently fails after exhausting all retries.

  • onRetryproperty
    onRetry?: (attempt: number, error: Error, delayMs: number) => void

    Invoked when a transient delivery error triggers a retry attempt with backoff delay.

MailLogger

interface

Structured logger interface for mail delivery operations and debugging.

interface MailLogger

4 members

  • debug
    debug(...args: unknown[]): void

    Log diagnostic or low-level trace messages.

  • info
    info(...args: unknown[]): void

    Log informational delivery notices.

  • warn
    warn(...args: unknown[]): void

    Log operational warnings.

  • error
    error(...args: unknown[]): void

    Log delivery and runtime errors.

MailProxyFunction

interface

Callable function signature for the global proxy facade.

15 members

  • to
    to<TTemplates extends Record<string, Record<string, unknown>> = RegisteredTemplates>(...recipients: RecipientInput[]): MailBuilder<TTemplates>

    Compose an email targeting one or more recipients using default mailer.

  • compose
    compose<TTemplates extends Record<string, Record<string, unknown>> = RegisteredTemplates>(): MailBuilder<TTemplates>

    Create a fluent builder session using default mailer.

  • send
    send(options: DirectSendOptions): Promise<SendResult>

    Directly dispatch an email using default mailer.

  • batch
    batch(items: Array<DirectSendOptions | MailBuilder<any>>): Promise<{ results: SendResult[]; total: number; failed: number; }>

    Concurrently send multiple emails using default mailer.

  • verify
    verify(): Promise<boolean>

    Verify default transport connection.

  • close
    close(): Promise<void>

    Close default transport connections.

  • drain
    drain(): Promise<void>

    Drain in-flight background deliveries on default mailer.

  • sent
    sent(): readonly SentMemoryEmail[]

    In memory mode, retrieve sent emails on default mailer.

  • lastSent
    lastSent(): SentMemoryEmail | undefined

    In memory mode, retrieve most recent email on default mailer.

  • sentCount
    sentCount(): number

    In memory mode, retrieve sent count on default mailer.

  • findSent
    findSent(predicate: (email: SentMemoryEmail) => boolean): SentMemoryEmail[]

    In memory mode, find sent emails matching predicate on default mailer.

  • clearSent
    clearSent(): void

    In memory mode, clear sent emails on default mailer.

  • reset
    reset(): void

    In memory mode, reset sent emails and metrics on default mailer.

  • stats
    stats(): MailStats

    Get metrics stats from default mailer.

  • [call]call
    (): YattaMailer<TTemplates>

    Access the default configured instance.

MailRateLimitOptions

interface

Rate limiting and concurrency controls for outbound email dispatch.

3 members

  • maxproperty
    max?: number

    Maximum messages allowed within the time window (default: unlimited).

  • windowMsproperty
    windowMs?: number

    Rolling time window in milliseconds for token refill (default: `1000` ms).

  • maxConcurrencyproperty
    maxConcurrency?: number

    Maximum concurrent SMTP deliveries allowed simultaneously (default: `5`).

MailRegister

interface

Global interface mergeable by application code for template type safety.

interface MailRegister
tsts
declare module "../types/mail" {  interface MailRegister {    templates: {      welcome: { name: string; verifyUrl: string };      resetPassword: { email: string; token: string; expiresMinutes: number };    };  }}

MailStats

interface

Aggregated operational metrics and delivery statistics tracked by .

interface MailStats

8 members

  • sentproperty
    sent: number

    Total count of successfully accepted email dispatches.

  • failedproperty
    failed: number

    Total count of failed deliveries that exhausted all retries.

  • rejectedproperty
    rejected: number

    Total count of recipients explicitly rejected by SMTP relays.

  • retriesproperty
    retries: number

    Total count of retry attempts executed due to transient delivery errors.

  • queuedproperty
    queued: number

    Total count of background asynchronous deliveries queued.

  • dryRunproperty
    dryRun: number

    Total count of emails processed in dryRun mode without network transmission.

  • totalDeliveryTimeMsproperty
    totalDeliveryTimeMs: number

    Cumulative milliseconds spent in SMTP network transmission.

  • averageDeliveryTimeMsproperty
    averageDeliveryTimeMs: number

    Average milliseconds spent per successful email delivery.

SendResult

interface

Result returned upon sending or previewing an email.

interface SendResult

6 members

  • messageIdproperty
    messageId: string

    Unique message identifier assigned by transport or SMTP relay.

  • acceptedproperty
    accepted: string[]

    List of recipient addresses accepted by the relay.

  • rejectedproperty
    rejected: string[]

    List of recipient addresses rejected by the relay.

  • failedproperty
    failed: boolean

    Whether the delivery encountered rejection or failures.

  • previewUrlproperty
    previewUrl?: string | false

    Web URL for previewing test emails in `"ethereal"` development mode.

  • rawproperty
    raw?: unknown

    Raw response object returned by underlying Nodemailer transport.

SentMemoryEmail

interface

Record of an email captured in-memory during tests in `"memory"` mode.

interface SentMemoryEmail

2 members

  • optionsproperty
    options: SendMailOptions

    Nodemailer send options compiled for this email.

  • sentAtproperty
    sentAt: Date

    Timestamp when the email was recorded in memory.

TemplateRenderResult

interface

Output components produced by compiling or rendering an email template.

3 members

  • subjectproperty
    subject?: string

    Optional subject line generated by the template.

  • htmlproperty
    html: string

    Compiled HTML email body.

  • textproperty
    text?: string

    Optional plain-text fallback content. Generated automatically if omitted.

EmailAddress

type

Represents 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

type

Email urgency level controlling client presentation and priority headers.

type MailPriority = "high" | "normal" | "low"

MailProvider

type

Supported built-in email provider presets.

type MailProvider = "smtp" | "gmail" | "resend" | "postmark" | "sendgrid" | "mailgun" | "brevo" | "ses"

MailProxy

type

Union proxy type combining and .

Prettify

type

Utility type expanding nested object properties for clearer IDE IntelliSense previews.

type Prettify<T> = { [K in keyof T]: T[K]; } & {}

RecipientInput

type

A single recipient address or an array of recipient addresses.

RegisteredTemplates

type

Extracts 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

type

Transformation 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

type

Definition 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)
Tip
Most of the types above are inferred. You rarely import AuthConfig or JobPayload — declaring your schema once is enough for the rest to follow. See Typed keys.