xtr-dev

payload mailing

by xtr-dev
Email
v3
^3.37.0

Overview

Summary generated from the README

Adds email-templates and emails collections to Payload for authoring rich-text templates and tracking delivery status. Emails are sent through a registered process-email job task with retries, scheduling and priorities, using the configured Payload email adapter. Requires Payload 3.37 or newer and the Lexical editor package; the collections deny all access until you grant it.

Features

  • Rich-text email templates with LiquidJS, Mustache or simple engines, or a custom renderer
  • Reusable layouts with a default layout and per-template selection
  • Queued sending with scheduledAt, priority, retry attempts and retry delay
  • Immediate sending option and renderTemplate helper to preview without sending
  • Required variable checks before queueing and HTML escaping by default
  • Deny-by-default access control on the emails and templates collections

Use cases

  • Send welcome, invite and password reset emails from editable templates
  • Schedule emails for later delivery and retry failed sends in the background
  • Keep branded email layouts consistent across many templates

From the author

Template-based email system with scheduling and job processing for PayloadCMS

Installation

npm i @xtr-dev/payload-mailing

1

Stars

0

Forks

0

Open Issues

1 weeks ago

Last Updated

613

Weekly Downloads

v0.9.0

npm Version

234.3 KB

Unpacked Size

0

Dependencies

GitHub stars

10 since Sep 6

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20261
Dec 4, 20261
Dec 3, 20261
Dec 2, 20261
Dec 1, 20261
Nov 30, 20261
Nov 29, 20261
Nov 28, 20261
Nov 27, 20261
Nov 26, 20261
Nov 25, 20261
Nov 24, 20261
Nov 23, 20261
Nov 22, 20261
Nov 21, 20261
Nov 20, 20261
Nov 19, 20261
Nov 18, 20261
Nov 17, 20261
Nov 16, 20261
Nov 15, 20261
Nov 14, 20261
Nov 13, 20261
Nov 12, 20261
Nov 11, 20261
Nov 10, 20261
Nov 9, 20261
Nov 8, 20261
Nov 7, 20261
Nov 6, 20261
Nov 5, 20261
Nov 4, 20261
Nov 3, 20261
Nov 2, 20261
Nov 1, 20261
Oct 31, 20261
Oct 30, 20261
Oct 29, 20261
Oct 28, 20261
Oct 27, 20261
Oct 26, 20261
Oct 25, 20261
Oct 24, 20261
Oct 23, 20261
Oct 22, 20261
Oct 21, 20261
Oct 20, 20261
Oct 19, 20261
Oct 18, 20261
Oct 17, 20261
Oct 16, 20261
Oct 15, 20261
Oct 14, 20261
Oct 13, 20261
Oct 12, 20261
Oct 11, 20261
Oct 10, 20261
Oct 9, 20261
Oct 8, 20261
Oct 7, 20261
Oct 6, 20261
Oct 5, 20261
Oct 4, 20261
Oct 3, 20261
Oct 2, 20261
Oct 1, 20261
Sep 30, 20261
Sep 29, 20261
Sep 28, 20261
Sep 27, 20261
Sep 26, 20261
Sep 25, 20261
Sep 24, 20261
Sep 23, 20261
Sep 22, 20261
Sep 21, 20261
Sep 20, 20261
Sep 19, 20261
Sep 18, 20261
Sep 17, 20261
Sep 16, 20261
Sep 15, 20261
Sep 14, 20261
Sep 13, 20261
Sep 12, 20261
Sep 11, 20261
Sep 10, 20261
Sep 9, 20261
Sep 8, 20261
Sep 7, 20261
Sep 6, 20261
npm weekly downloads

781+753 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 2026781
Dec 4, 2026802
Dec 3, 2026799
Dec 2, 2026759
Dec 1, 2026850
Nov 30, 2026895
Nov 29, 2026667
Nov 28, 2026540
Nov 27, 2026362
Nov 26, 2026393
Nov 25, 2026423
Nov 24, 2026322
Nov 23, 2026246
Nov 22, 2026149
Nov 21, 202699
Nov 20, 2026101
Nov 19, 202697
Nov 18, 2026138
Nov 17, 2026161
Nov 16, 2026208
Nov 15, 2026212
Nov 14, 2026214
Nov 13, 2026258
Nov 12, 2026291
Nov 11, 2026253
Nov 10, 2026237
Nov 9, 2026189
Nov 8, 2026183
Nov 7, 2026191
Nov 6, 2026168
Nov 5, 2026104
Nov 4, 202671
Nov 3, 202656
Nov 2, 202655
Nov 1, 202651
Oct 31, 202634
Oct 30, 202610
Oct 29, 20269
Oct 28, 20266
Oct 27, 20265
Oct 26, 202617
Oct 25, 202647
Oct 24, 202699
Oct 23, 202699
Oct 22, 2026100
Oct 21, 2026103
Oct 20, 2026106
Oct 19, 202695
Oct 18, 202662
Oct 17, 202611
Oct 16, 202611
Oct 15, 202669
Oct 14, 2026110
Oct 13, 2026138
Oct 12, 2026153
Oct 11, 2026168
Oct 10, 2026167
Oct 9, 2026169
Oct 8, 2026113
Oct 7, 202672
Oct 6, 202642
Oct 5, 202626
Oct 4, 202612
Oct 3, 202624
Oct 2, 202628
Oct 1, 202625
Sep 30, 202629
Sep 29, 202637
Sep 28, 202638
Sep 27, 202637
Sep 26, 202627
Sep 25, 202621
Sep 24, 202672
Sep 23, 202666
Sep 22, 202658
Sep 21, 2026109
Sep 20, 2026111
Sep 19, 2026108
Sep 18, 2026110
Sep 17, 202661
Sep 16, 202662
Sep 15, 202661
Sep 14, 202611
Sep 13, 20269
Sep 12, 202613
Sep 11, 202617
Sep 10, 202616
Sep 9, 202618
Sep 8, 202620
Sep 7, 202621
Sep 6, 202628

Each point is npm's rolling 7-day download count.

Health Score

70/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1055702159-root.svg)](https://payloaddirectory.dev/plugins/1055702159-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1055702159-root"><img src="https://payloaddirectory.dev/badge/1055702159-root.svg" alt="Payload Directory"></a>
Updated Nov 28, 2026Created Sep 12, 2025Published Nov 27, 2026

README

@xtr-dev/payload-mailing

npm version

Template-based email for PayloadCMS 3.x — templates, layouts, scheduling, and job-queue processing, all through Payload collections you already know.

v0.x — minor versions may contain breaking changes until 1.0.

Install

pnpm add @xtr-dev/payload-mailing @payloadcms/richtext-lexical

@payloadcms/richtext-lexical is a required peer dependency: the templates collection uses it as the default rich-text editor. If your app already uses the Lexical editor (Payload's default), you have it installed already.

Quick Start

Add the plugin plus an email adapter:

import { buildConfig } from 'payload'
import { mailingPlugin } from '@xtr-dev/payload-mailing'
import { nodemailerAdapter } from '@payloadcms/email-nodemailer'

export default buildConfig({
  email: nodemailerAdapter({ defaultFromAddress: '[email protected]', transport: { /* SMTP */ } }),
  plugins: [
    mailingPlugin({
      defaultFrom: '[email protected]',
      collections: {
        // Required — collections deny all access by default. See "Access Control".
        // Grant staff only: sent emails contain sign-in links and other per-recipient secrets.
        emails: { access: { read: ({ req: { user } }) => user?.role === 'admin' } },
        templates: { access: { read: ({ req: { user } }) => user?.role === 'admin' } },
      },
    }),
  ],
})

This adds two collections under a Mailing admin group: email-templates (author templates) and emails (delivery + status tracking).

Access Control

The mailing collections deny every operation by default. Payload's built-in default grants access to any authenticated user, which in an app with front-end/non-admin users would expose email content, recipients, and templates. Until you grant access explicitly, no one can read or manage these collections via the REST/GraphQL API or admin panel — but sending still works, since the plugin sends through Payload's Local API (which bypasses access control).

Grant access via the collection overrides. Your functions are merged on top of the deny-all default, so any operation you don't set stays denied:

mailingPlugin({
  collections: {
    emails: {
      access: {
        read:   ({ req: { user } }) => user?.role === 'admin',
        create: ({ req: { user } }) => user?.role === 'admin',
        update: ({ req: { user } }) => user?.role === 'admin',
        delete: ({ req: { user } }) => user?.role === 'admin',
      },
    },
    // templates: { access: { … } }
  },
})

Keep emails staff-only. Each sent email stores its variables and rendered body, which often hold sign-in links, confirmation links and one-time codes, so granting read to every signed-in user lets any account take over another. Granting create lets any account send mail from your domain. Your app's own code sends through sendEmail (Local API) and needs no access rule.

access is the standard Payload access control API. The same override object also accepts custom fields, hooks, admin, etc.

Sending Email

import { sendEmail } from '@xtr-dev/payload-mailing'

// From a template
await sendEmail(payload, {
  template: { slug: 'welcome-email', variables: { firstName: 'John' } },
  data: {
    to: '[email protected]',
    scheduledAt: new Date(Date.now() + 3600_000), // optional: send later
    priority: 1,                                   // optional: 1 = highest
  },
})

// Or with your own content
await sendEmail(payload, {
  data: { to: '[email protected]', subject: 'Hi', html: '<h1>Hi</h1>' },
})

Emails are queued and sent in the background (see Jobs). Pass processImmediately: true to send synchronously, or queue to route a single send's job onto a named queue (e.g. 'high') instead of the plugin's queue option.

With processImmediately, sendEmail resolves (with the sent email) only when the email actually went out. If the email was created and queued but not sent inline (the delivery failed, e.g. your SMTP server is down, or the job could not be run), sendEmail throws an ImmediateProcessingError. The email is not lost: it is back to pending and is retried by your job runner after retryDelay, like any failed send (see Jobs). The error's email (with its current status and error) and jobId tell you which email it was. If "queued is fine" for your caller, catch the error and treat the send as queued instead of failed:

import { ImmediateProcessingError, sendEmail } from '@xtr-dev/payload-mailing'

try {
  await sendEmail(payload, { template: { slug: 'invite' }, data: { to }, processImmediately: true })
} catch (error) {
  if (!(error instanceof ImmediateProcessingError)) throw error
  // Created and queued, not lost: error.email.id will be retried by the queue.
}

Any other error (validation, template, database) means no email was created. If that inline try was the email's last allowed attempt (retryAttempts: 1), error.email.status is failed and it is not retried. An email with a future scheduledAt is not sent inline and does not throw; it stays pending until it is due.

Templates

Author templates in the admin (Mailing → Email Templates): a slug, subject, rich-text content, and optional declared variables. Reference data with {{ }}, e.g. Hello {{ user.name }}! or {{ createdAt | formatDate: "long" }}.

  • Engines — set templateEngine to liquidjs (default), mustache, or simple, or supply templateRenderer: (tpl, vars) => string for your own.
  • Escaping — HTML-body variables are HTML-escaped by default (opt out with LiquidJS {{ x | raw }} / Mustache {{{ x }}}); subject and text are verbatim. LiquidJS {% echo x %} is escaped the same way as {{ x }}, literals included; write {% echo x | raw %} for intentional HTML. Use | raw only on values you trust. This needs liquidjs 10.30.1 or newer, which the plugin installs; older versions wrote echo output unescaped.
  • HTML vs. text values — wrap a variable in perPart({ html, text }) to give the HTML body one value and the plain-text body (and subject) another, e.g. a link button as markup in HTML and as Log in: https://… in text. The HTML value is still escaped unless you use | raw / {{{ }}}.
  • Links — rich-text link URLs can hold variables, e.g. {{siteUrl}}/account or {{resetUrl}}. Leave out spaces inside the braces (the link field rejects URLs with spaces). The value is HTML-escaped but its scheme is not checked, so pass only trusted URLs.
  • Filters (LiquidJS) — formatDate ("short", "long" or default), formatCurrency and capitalize. Set locale (e.g. 'nl-NL'), currency (e.g. 'EUR') and timeZone (e.g. 'Europe/Amsterdam') in the plugin config, or override per use: {{ d | formatDate: "long", "nl-NL" }}, {{ total | formatCurrency: "EUR", "nl-NL" }}.
  • Required variables — mark declared variables Required and a send missing one is rejected before it's queued. Dotted names such as user.name are checked as nested paths. Opt-in; declare nothing to skip checks.

Render without sending: renderTemplate(payload, slug, vars) → { html, text, subject }.

Layouts

Define reusable wrappers once and inject a template's body at {{ content }}:

mailingPlugin({
  layouts: {
    branded: { html: `<html><body><main>{{ content }}</main></body></html>` },
  },
  defaultLayout: 'branded', // applied to templates that don't pick their own
})

Templates then get a Layout select (with Use default / None). Layout variables are always HTML-escaped; content is injected without double-encoding. Fully opt-in — with no layouts, templates render exactly as before.

Jobs

The plugin registers its process-email task automatically. Sending (or creating an emails doc) queues one job per email on the plugin's queue, delayed until scheduledAt when set. You need a job runner: Payload's jobs.autoRun cron for that queue, or your own payload.jobs.run() calls.

Emails move through pending → processing → sent / failed. A send error puts the email back to pending and queues a new process-email job (on the same queue) that runs once retryDelay has passed, so your job runner retries it without extra code. After retryAttempts tries (default 3) the email is marked failed and is not sent again unless you ask for it with retryFailedEmails(payload). processEmails(payload) sends up to 50 due pending emails per call (highest priority, then oldest first, skipping emails whose last failed try is more recent than retryDelay); call it from a scheduled task if you don't run a job runner, or as a safety net. An email is only ever sent by the run that claims it, so a retry job and processEmails never both send it. An email left processing by a crashed process is released by processEmails / retryFailedEmails once processingTimeout has passed, as a failed attempt.

processAllEmails(payload) is the one call to put on a schedule: it runs processEmails, then retries failed emails that are below retryAttempts again (which only happens after you raise that option). Emails that used up their attempts stay failed and are skipped on every later run.

To queue an email from a Payload job or workflow, register the schedule-email task from the /tasks subpath:

import { ScheduleEmailTask } from '@xtr-dev/payload-mailing/tasks'

export default buildConfig({ jobs: { tasks: [ScheduleEmailTask] } })

await payload.jobs.queue({ task: 'schedule-email', input: { to: '[email protected]', templateSlug: 'welcome' } })

Options

OptionDescription
defaultFrom / defaultFromNameDefault sender for emails that don't set one.
retryAttemptsMaximum send attempts per email (default 3). The attempt that reaches it marks the email failed; automatic retries and processAllEmails then leave it alone.
retryDelayWait (ms) after a failed send before it is retried (default 300000).
processingTimeoutTime (ms) after which an email stuck in processing (its process crashed mid-send) is released for a retry (default 900000). Keep it above your slowest send: a send still running past it may go out twice.
queueJob queue name (default 'default'). A single sendEmail call can override it with its own queue option.
templateEngine'liquidjs' | 'mustache' | 'simple'.
templateRendererCustom (tpl, vars) => string | Promise<string>.
strictTemplatestrue makes a template parse/render error throw a TemplateRenderError (so sendEmail rejects) instead of falling back to plain {{ name }} substitution. Default false.
layouts / defaultLayoutNamed layout wrappers and the default one.
locale / currency / timeZoneDefaults for the formatDate / formatCurrency filters (otherwise en-US / USD / server time zone).
adminPreviewLive in-admin render preview; true by default. Set false to skip it (and the payload generate:importmap step).
collectionsRename ('slug') or override ({ access, fields, … }) the emails/templates collections.
beforeSend(options, email) => options hook to mutate the send just before delivery.
resolveInternalLink(fields) => url for rich-text links to other documents (fields.doc.relationTo / fields.doc.value). Without it, internal links render as plain text.
richTextEditorCustom Lexical editor config for the templates collection's content field, passed through as RichTextField['editor'].
initOrder'before' (default) sets up payload.mailing before the host app's own onInit runs; 'after' runs the host's onInit first.

API

ExportPurpose
sendEmail(payload, options)Queue (or immediately send) a template/direct email.
renderTemplate(payload, slug, vars)Render { html, text, subject } without sending.
processEmails(payload)Send up to 50 due pending emails.
processAllEmails(payload)processEmails, then retryFailedEmails limited to emails with attempts left. Never retries an email that used up retryAttempts, so it is safe to schedule.
retryFailedEmails(payload, options?)Manual retry: give up to 20 failed emails one more try each, oldest first, once retryDelay has passed since their last attempt, including emails that used up retryAttempts. If that try fails too, the email stays failed. Don't schedule it as is (it would retry forever); pass { onlyWithAttemptsLeft: true } to skip emails that reached retryAttempts.
getMailing(payload)Get the mailing context (service, config, slugs).
escapeHtml(str) / safeUrl(url)Escape text for HTML / allow only http(s), mailto and relative URLs.
perPart({ html, text })Give a variable separate HTML and plain-text values.
ImmediateProcessingError / TemplateRenderErrorThrown by processImmediately sends that were queued but not sent inline / by strictTemplates render errors.

sendEmail<Email>(…) is generic over your generated Email type for type-safe custom fields.

Requirements

PayloadCMS ^3.37.0 · Node.js ^18.20.2 || >=20.9.0

@payloadcms/ui and react are optional peers, used only by the admin preview (adminPreview); a Payload app with the admin panel already has them.

Contributing

Issues and PRs welcome at the repository; see DEVELOPMENT.md for local setup. MIT licensed.

Similar plugins