@growth-labs/mailer

中文文档
0.8.2发布于 2026/10/27TypeScriptES Module近 30 天下载 4945

Queue-based email sending engine for Astro + Cloudflare. Newsletter subscriptions with double opt-in, campaign sending, open/click tracking, unsubscribe management. Uses Cloudflare Queues for async delivery.

原始使用文档
文档目录10 节
  1. When to use this vs @growth-labs/email
  2. Config
  3. Components without delivery routes
  4. Production patterns
  5. What It Injects
  6. D1 Tables (prefixed gl_ )
  7. Wrangler Bindings
  8. Email Sending Flow
  9. Key Patterns
  10. Analytics Events

@growth-labs/mailer

Queue-based email sending engine for Astro + Cloudflare. Newsletter subscriptions with double opt-in, campaign sending, open/click tracking, unsubscribe management. Uses Cloudflare Queues for async delivery.

"The engine, not the driver." This package sends emails. What to send and to whom is the consumer's concern (e.g. @fulcrum/dispatch layers editorial intelligence on top).

If you only need immediate transactional delivery from a Worker with no subscriber state or queueing, use @growth-labs/email instead.

Astro 6 note: injected routes read D1 and Queue bindings from cloudflare:workers env; no locals.runtime shim is required.

When to use this vs @growth-labs/email

Use @growth-labs/mailer (this package) for newsletter and campaign workflows. Use @growth-labs/email for transactional one-off sends. See the @growth-labs/email README for the full distinction.

Both integrations register the package's existing virtual config types through Astro's astro:config:done type injection. No consumer-owned declaration is needed for virtual:growth-labs/mailer/config; runtime route selection is unchanged.

Config

import mailer from '@growth-labs/mailer'

mailer({
  senderName: 'FEDweek',
  fromAddress: '[email protected]',
  replyTo: '[email protected]',
  d1Binding: 'SITE_DB',
  queueBinding: 'EMAIL_QUEUE',
  turnstileSiteKey: '...',
  turnstileSecretBinding: 'TURNSTILE_SECRET_KEY', // Optional; this is the default
  doubleOptIn: true,
  topics: ['daily-digest', 'breaking-news'],     // Optional topic-based subscriptions
  signingSecretBinding: 'MAILER_SIGNING_SECRET', // Optional; this is the default
  siteUrl: 'https://fedweek.com',
  brand: {
    logoUrl: 'https://media.fedweek.com/logos/email.png',
    primaryColor: '#1a365d',
    accentColor: '#e53e3e',
    footerText: '© FEDweek. All rights reserved.',
  },
  analyticsEnabled: true,                        // Emit email events to @growth-labs/analytics
  analyticsBinding: 'ANALYTICS',                 // WAE binding used when analytics is enabled
  webhookSignature: {
    enabled: true,
    secret: import.meta.env.MAILER_WEBHOOK_SECRET,
  },
})

This integration registers the newsletter routes and components listed below. For a new subscriber, the subscribe route records the subscriber and sends a confirmation email when doubleOptIn is enabled, or a welcome email when it is not.

Components without delivery routes

Use mailerComponents instead of mailer when rendering SubscribeForm with an endpoint owned by the consumer, or in a private preview with delivery disabled:

import { mailerComponents } from '@growth-labs/mailer'

mailerComponents({
  turnstileSiteKey: 'public-site-key',
  subscribePath: '/api/newsletter/subscribe', // Optional; this is the default
  topics: ['daily-digest'],                 // Optional
})

This installs only the existing form configuration Vite plugin. It injects no routes or tracking middleware and requires no D1, Queue, sender or secret binding. Only these three public options are accepted; secret and delivery options fail validation. The form still submits to subscribePath: this integration does not implement subscription delivery or disable the form. The consumer must provide a Turnstile-protected endpoint, or keep delivery unavailable in its private preview. Choose one mailer integration per site. The default mailer integration retains its full route, middleware and runtime security behavior.

Production patterns

from vs replyTo. A common pattern is fromAddress: '[email protected]' paired with replyTo: '[email protected]'. The from lives on a domain you've verified with Cloudflare Email Sending (typically a mail. subdomain); replyTo points at a real human inbox readers can write back to. replyTo is also a per-message override on sendTransactional and a per-site field on SiteMailerConfig (realm pattern, since 0.4.0).

Don't bake fallbacks for fromAddress. The schema requires a valid email (z.string().email()) and ships no default — that's intentional. A consumer-side fallback like process.env.MAILER_FROM_ADDRESS ?? '[email protected]' is a foot-gun: if the env var is missing at deploy time the fallback domain probably isn't verified with Cloudflare Email Sending, every send returns unauthorized_sender, and the queue retries until the budget kills the message. Fail loudly at build/deploy when the env var is missing instead — the schema can't catch your fallback.

Secrets resolve at request time. Bind TURNSTILE_SECRET_KEY and MAILER_SIGNING_SECRET on the Worker. Plain Worker secrets and Secrets Store bindings are both supported; Secrets Store bindings are read with async .get() and cached per isolate. Missing or empty production bindings return a 503 before subscriber writes. Build-time literal options are ignored outside localhost.

What It Injects

Routes:

  • POST /api/newsletter/subscribe — Turnstile-protected subscription
  • GET /api/newsletter/confirm?token=... — Double opt-in confirmation
  • GET /api/newsletter/unsubscribe?token=... — One-click unsubscribe
  • GET/POST /email/preferences?token=... — Preference center page
  • POST /api/email/webhook — ESP webhook receiver (delivery, bounce, complaint), optional HMAC signature verification
  • GET /api/email/open/:trackingId — Open tracking pixel
  • GET /api/email/click/:trackingId — Click tracking redirect

Components:

  • <SubscribeForm /> — Newsletter signup form with Turnstile
  • <PreferenceCenter /> — Topic subscription management

D1 Tables (prefixed gl_)

  • gl_subscribers — subscriber records (email, name, status, topics, confirmed_at)
  • gl_email_sends — send log (status: queued → sent → delivered → opened → clicked)

Wrangler Bindings

[[d1_databases]]
binding = "SITE_DB"
database_id = "..."

[[queues.producers]]
binding = "EMAIL_QUEUE"
queue = "email-sends"

[[queues.consumers]]
queue = "email-sends"
max_batch_size = 10

[[analytics_engine_datasets]]
binding = "ANALYTICS"
dataset = "your_analytics_dataset"

[[secrets_store_secrets]]
binding = "TURNSTILE_SECRET_KEY"
store_id = "..."
secret_name = "your-turnstile-secret"

[[secrets_store_secrets]]
binding = "MAILER_SIGNING_SECRET"
store_id = "..."
secret_name = "your-mailer-signing-secret"

Email Sending Flow

  1. Consumer calls sendTransactional(), sendCampaign(), or sendDigest() → message enqueued
  2. Queue consumer dequeues → sends via Cloudflare Email Sending with retry on retryable failures
  3. Status updated in gl_email_sends: queued → sent → delivered/bounced
  4. Open/click tracking updates status further

Key Patterns

  • Virtual module: virtual:growth-labs/mailer/config
  • Runtime bindings: import { env } from 'cloudflare:workers'
  • Status never downgrades (sent → delivered → opened → clicked)
  • List-Unsubscribe header on every email (RFC 8058)
  • Turnstile on subscribe endpoint (+ IP rate limiting as backup)
  • Provider failover logged for observability
  • WAE events via the configured Analytics Engine binding — fire-and-forget, non-blocking, and compatible with bindings whose writeDataPoint() returns void
  • Cloudflare Email Sending uses the current structured html payload and forwards replyTo plus custom headers to the binding
  • .astro component files ship as source, not compiled

Analytics Events

When analyticsEnabled is true and the configured analyticsBinding exists, the package writes WAE data points for newsletter_subscribed, newsletter_confirmed, newsletter_unsubscribed, newsletter_opened, newsletter_clicked, newsletter_delivered, newsletter_bounced, newsletter_complained, newsletter_sent, and newsletter_send_failed.

版本与发布记录

@growth-labs/mailer 共发布 27 个版本,首次发布于 2026/04/13;过去 12 个月发布了 27 个版本。

版本发布日期距今
0.8.2latest2026/10/2720 天前
0.8.12026/10/2721 天前
0.8.02026/10/2621 天前
0.7.02026/10/2523 天前
0.6.52026/10/2424 天前
0.6.42026/10/2424 天前

关于 @growth-labs/mailer 的常见问题

@growth-labs/mailer 是什么?

Queue-based email sending engine for Astro + Cloudflare. Newsletter subscriptions with double opt-in, campaign sending, open/click tracking, unsubscribe management. Uses Cloudflare Queues for async delivery.

如何安装 @growth-labs/mailer?

在项目目录运行 npm install @growth-labs/mailer,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:astro(^6.1.10 || ^7.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@growth-labs/mailer 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@growth-labs/mailer 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@growth-labs/mailer 可以商用吗?

@growth-labs/mailer 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@growth-labs/mailer 的下载量有多少?

根据 npm 官方下载统计,@growth-labs/mailer 在 2026/10/17 – 2026/11/15 这 30 天内被下载 4,945 次,日均约 165 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@growth-labs/mailer 还在维护吗?

最新版本 0.8.2 发布于 2026/10/27(20 天前);至今共发布 27 个版本,其中过去 12 个月发布了 27 个;首次发布于 2026/04/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。