NestJS中文文档
应用 / 邮件
已译 191/191

邮件

@nestjs/mail 从 Nest 应用发送邮件:由转义过的 HTML 模板渲染出邮件类,经 SMTP 或邮件 API 发出,并可在测试中回读。

提示

想在完整应用中从队列发信、带重试且不重复发送,请参阅在 Node.js 中发送邮件并运行后台任务。

顾客在猫粮与用品网店下单后,期望一分钟内收到确认邮件:商品清单、总额、订单链接,以及 PDF 发票。要把这封邮件发好,光调用一个 SMTP 库远远不够:

  • HTML 必须安全。 商品名或顾客名会进入标记。未转义时,像 <script> 这样的名字或多余的 & 会破坏布局,甚至更糟。
  • 邮件必须能扛住故障。 邮件服务器会灰名单、限流、宕机。在请求内发送失败,要么让一笔已提交的订单失败,要么丢掉这封邮件。
  • 测试必须能看到发出了什么。 测「顾客收到带订单链接的确认信」,需要的是渲染后的邮件及其链接,而不是一次被 mock 的方法调用。

@nestjs/mail 覆盖了这些。邮件类是可注入的提供者,从带类型的数据渲染主题与正文,因此可以注入你的其他提供者,例如仓储或 PDF 渲染器。正文来自 HTML 模板文件,由内置的小引擎渲染(它会转义插入的每个值),也可换成 Handlebars 或任何你接入的引擎。传输层负责投递:SMTP(基于 node:net 与 node:tls 实现),以及通过 HTTP API 的 Resend、Postmark、SendGrid 和 Amazon SES。测试把传输层换成内存实现,读取它收到的邮件。除 Nest 本身外,该包没有依赖。

本教程会为商店的订单 API 加上订单确认邮件:

  • 开发环境把每封邮件写成 .eml 文件而不发送。
  • 确认信是一个邮件类,渲染 HTML 模板,套在所有邮件共享的布局中,附带发票并把 logo 内联。
  • 一条预览路由在浏览器中展示邮件而不发送。
  • 邮件在订单提交后通过 outbox 发出,带重试与死信。
  • 生产环境经 SMTP 或 Resend 发送,由环境变量选择。

安装

首先,安装所需的依赖:

$ npm i --save @nestjs/mail

注册邮件模块

在根模块中、DrizzleModule 旁边注册 MailModule。邮件教程需要数据库来存放顾客及其订单,以及 outbox 的表——邮件正是通过它在订单提交后发送。开发环境中,FileMailTransport 把每封邮件写入 var/mail 下的文件而不发送,FileTemplateEngine 从 mail/templates 中的 HTML 文件渲染正文。它导入的功能模块在后续小节中构建:

app.module.ts
import { Module } from '@nestjs/common';
import { DrizzleModule } from '@nestjs/drizzle';
import { FileMailTransport, FileTemplateEngine, MailModule } from '@nestjs/mail';
import { drizzle } from 'drizzle-orm/node-postgres';
import { join } from 'node:path';
import * as schema from './database/schema.js';
import { NotificationsModule } from './notifications/notifications.module.js';
import { OrdersModule } from './orders/orders.module.js';

@Module({
  imports: [
    DrizzleModule.forRootAsync({
      // DATABASE_URL 上的 pg 连接池:顾客与订单,以及 outbox 的表
      useFactory: () => ({ drizzle, connection: process.env.DATABASE_URL!, schema }),
    }),
    MailModule.forRoot({
      // 开发环境:每封邮件变成 var/mail 下的 .eml 文件,不离开本机
      transport: new FileMailTransport({ directory: 'var/mail' }),
      // 邮件正文是 mail/templates 中的 HTML 文件,套在 mail/templates/layout.html 中
      templates: new FileTemplateEngine({
        dir: join(import.meta.dirname, 'mail/templates'),
        layout: 'layout',
        // 开发环境每封邮件都重新读文件,改动无需重启即可生效
        cache: process.env.NODE_ENV === 'production',
      }),
      from: 'Orders <orders@example.com>',
    }),
    OrdersModule,
    NotificationsModule,
  ],
})
export class AppModule {}
  • transport:邮件如何离开应用。所有传输层都继承抽象类 MailTransport,它同时也是注入标记,因此测试可用 overrideProvider(MailTransport) 替换。FileMailTransport 用于开发:用任意邮件客户端打开 .eml 文件,就能看到将要发出的内容。它写入本地磁盘、不会送达任何人,因此生产环境会改用 SMTP 或 Resend。
  • templates:渲染指定了模板的邮件。FileTemplateEngine 从 dir 读取 .html 文件,并把每封邮件套进 layout 模板 mail/templates/layout.html。相对的 dir 按工作目录解析;用 import.meta.dirname 构建时,它指向编译后的 app.module.js 旁边,无论应用从何处启动。编译后的模板会被缓存。关闭 cache(如这里在生产环境之外)时,每封邮件都重新读文件,改过的模板下一封邮件即生效,无需重启。
  • from:默认发件人。单封邮件可以覆盖。

TypeScript 编译器不会把 HTML 文件复制到 dist。请把模板加入 nest-cli.json 的资源,让它们落到 dist/mail/templates,与编译后的 app.module.js 相邻:

{
  "compilerOptions": {
    "assets": ["mail/templates/**/*"],
    "watchAssets": true
  }
}

有了 watchAssets,nest start --watch 会在你保存模板时把它复制到 dist。

提示

为简短起见,教程直接读取 process.env。在实际应用中,请通过 @nestjs/config 配合校验 schema 加载环境,让缺失的 DATABASE_URL 或 SMTP_URL 在启动时就终止应用,并在工厂中从 ConfigService 读取值。

MailModule 是全局的,提供 Mailer(发送邮件)与 MailEvents(报告发送成功与失败)。缺少 transport 或 from 无效会在启动时终止应用,并指明是哪个选项。

编写订单确认邮件

邮件正文是一个 HTML 模板。值写在双花括号之间,#each 之类的块会为列表的每个元素重复模板中的那一段:

mail/templates/order-confirmation.html
<p>Hi {{ customer.name }},</p>
<p>thank you for your order! We are packing it now.</p>
<table>
  <tr><th>Product</th><th>Qty</th><th>Price</th></tr>
  {{#each items}}
  <tr>
    <td>{{ name }}</td>
    <td>{{ quantity }}</td>
    <td>{{ price }}</td>
  </tr>
  {{/each}}
</table>
<p><strong>Total: {{ total }}</strong></p>
<p><a href="{{ orderUrl }}">View your order</a></p>

每封邮件都套在布局中。布局用三花括号把渲染后的邮件放到 body 处,并引入签名——一个位于 mail/templates/partials/signature.html 的局部模板:

mail/templates/layout.html
<!DOCTYPE html>
<html>
<body>
{{{ body }}}
{{> signature}}
</body>
</html>
mail/templates/partials/signature.html
<p>The customer care team</p>

邮件类实现 Mailable<TData>。它的 render() 方法接收数据,返回主题、模板名以及模板读取的上下文值:

notifications/order-confirmation.mail.ts
import { Injectable } from '@nestjs/common';
import type { Mailable } from '@nestjs/mail';
import type { Customer } from '../customers/customers.repository.js';
import type { Order } from '../orders/order.js';

export interface OrderConfirmation {
  order: Order;
  customer: Customer;
}

const SHOP_URL = process.env.SHOP_URL ?? 'https://shop.example.com';

@Injectable()
export class OrderConfirmationMail implements Mailable<OrderConfirmation> {
  render({ order, customer }: OrderConfirmation) {
    const price = (cents: number) => `$${(cents / 100).toFixed(2)}`;
    return {
      subject: `Your order #${order.number}`,
      // mail/templates/order-confirmation.html,套在布局中
      template: 'order-confirmation',
      // 模板展示的值,已准备好插入:价格已格式化,链接已构建
      context: {
        customer,
        items: order.items.map((item) => ({
          name: item.name,
          quantity: item.quantity,
          price: price(item.price * item.quantity),
        })),
        total: price(order.total),
        orderUrl: `${SHOP_URL}/orders/${order.id}`,
      },
    };
  }
}

模板是无逻辑的。它有值、#if、#unless 与 #each 块、局部模板和注释,但没有 helper,也没有表达式:需要代码的事,例如格式化价格或构建链接,都在邮件类中用 TypeScript 完成,有类型也有测试。语法是 Handlebars 的子集(见模板语法),因此模板可以原样迁移到其他引擎。

双花括号会转义值。名为 Feather wand toy <limited edition> 的商品会变成 Feather wand toy &lt;limited edition&gt;,顾客名无法注入标记。两条规则让出错变得困难:

  • 转义保护的是元素内容与带引号的属性值,因此双花括号的值只能放在这两处。值出现在标签内其他位置是编译错误:href= 后直接跟值,或值夹在属性之间。转义无法保护这两处(未加引号时,值中的空格会开启一个新属性)。请给属性值加引号,如上面的链接。
  • 三花括号原样插入值,用于你自己生成的 HTML。本教程中只有布局的 body 需要它。

缺失的值渲染为空,与 Handlebars 一致。在 #each 内,this 是当前元素,@index、@first 和 @last 描述其位置,元素上不存在的名称会到模板上下文中查找,因此某一行可以显示列表之外的值。无法编译的模板会让该邮件以永久性的 MailTemplateError 失败,错误会指明文件与位置:

order-confirmation.html:5:3: {{#each items}} is never closed (expected {{/each}})

没有纯文本模板。邮件器会从 HTML 推导纯文本部分:段落、表格行,以及写成 View your order (https://shop.example.com/orders/…) 的链接。不显示 HTML 的邮件客户端和垃圾邮件过滤器读的就是这部分。要自己写,请在 HTML 旁添加 order-confirmation.txt:引擎会用相同语法渲染它作为文本部分,但不做转义。

像其他可注入对象一样,把该类注册为提供者:

notifications/notifications.module.ts
import { Module } from '@nestjs/common';
import { OrderConfirmationMail } from './order-confirmation.mail.js';

@Module({
  providers: [OrderConfirmationMail],
})
export class NotificationsModule {}

然后在下单时发送。mailer.send() 接收邮件类与收件人,data 的类型来自该类的 render():

orders/orders.service.ts
async placeOrder({ customerId, items }: PlaceOrderDto): Promise<Order> {
  const customer = await this.customersRepository.findById(customerId);
  if (!customer) {
    throw new BadRequestException(`Unknown customer "${customerId}"`);
  }
  if (!items?.length) {
    throw new BadRequestException('An order needs at least one item');
  }

  const order = await this.db.transaction((tx) => this.insertOrder(tx, customerId, items));

  // 提交之后:绝不要在事务内发送,否则事务会一直开着、占着连接与锁,
  // 直到邮件服务器应答为止
  await this.mailer.send(OrderConfirmationMail, {
    to: { name: customer.name, address: customer.email },
    data: { order, customer },
  });
  return order;
}

收件人是带 name 与 address 的对象,因此含逗号或引号的名字仍是一个显示名。字符串也可以,例如 'Ada Lovelace <ada@example.com>',但字符串必须恰好包含一个地址:逗号分隔的列表会抛出,因此用户输入的名字永远无法追加收件人。多个收件人用数组。

下一单,var/mail 中就会出现文件。这能工作,但它在请求内、提交之后发送。下一节会解释为什么这还不够,并给出修复。

内联写邮件。 小到可以直接写在 TypeScript 里的邮件不需要模板文件。render() 用 html 标签模板构建 html 来替代 template 与 context:

notifications/order-confirmation.mail.ts
return {
  subject: `Your order #${order.number}`,
  html: html`
    <p>Hi ${customer.name},</p>
    <p>thank you for your order! We are packing it now.</p>
    <table>
      ${order.items.map(
        (item) => html`
          <tr>
            <td>${item.name}</td>
            <td>${item.quantity}</td>
            <td>${price(item.price * item.quantity)}</td>
          </tr>`,
      )}
    </table>
    // ...
};

html 按与模板相同的规则转义你插入的每个值:标签内的值必须位于带引号的属性值中,否则抛出。嵌套的 html 模板及其数组(如上面的表格行)原样插入,unsafeHtml() 插入你自己生成的 HTML——名字本身就是警告。mailer.send() 也接受 html,用于不经过邮件类的消息。

附带发票并预览邮件

发票是 PDF,由一个小提供者渲染。它用内置字体手写 PDF,以免示例引入依赖。真实应用这里会用 PDF 库或渲染服务。邮件只需要字节:

notifications/invoice-pdf.ts
@Injectable()
export class InvoicePdf {
  render(order: Order, customer: Customer): Buffer {
    const money = (cents: number) => `$${(cents / 100).toFixed(2)}`;
    const lines = [
      `Invoice ${order.number}`,
      `Date: ${order.placedAt.slice(0, 10)}`,
      `Bill to: ${customer.name}`,
      '',
      ...order.items.map((item) => `${item.quantity} x ${item.name}  ${money(item.price * item.quantity)}`),
      '',
      `Total: ${money(order.total)}`,
    ];
    // ...
  }
}

render() 随模板一起返回附件。发票是普通附件。logo 是内联图片:它的 cid 让它成为 HTML 的一部分,HTML 中用 cid:logo@example.com 引用它。每封邮件都有 logo,因此引用放在布局里:

mail/templates/layout.html
<!DOCTYPE html>
<html>
<body>
<p><img src="cid:logo@example.com" alt="Logo" width="120" height="32"></p>
{{{ body }}}
{{> signature}}
</body>
</html>

邮件类附上 logo 与发票:

notifications/order-confirmation.mail.ts
const LOGO = join(import.meta.dirname, 'assets/logo.png');

@Injectable()
export class OrderConfirmationMail implements Mailable<OrderConfirmation> {
  constructor(private readonly invoicePdf: InvoicePdf) {}

  render({ order, customer }: OrderConfirmation) {
    // ...
    return {
      subject: `Your order #${order.number}`,
      // mail/templates/order-confirmation.html,套在布局中
      template: 'order-confirmation',
      // ...
      attachments: [
        // 内联:布局中的 <img> 通过 cid 引用它
        { cid: 'logo@example.com', path: LOGO },
        { filename: `invoice-${order.number}.pdf`, content: this.invoicePdf.render(order, customer) },
      ],
    };
  }
}

在这个布局中渲染的每封邮件都要以同样方式附上 logo,否则页头会显示破图。模板在链接之后多一行 <p>Your invoice is attached.</p>。

附件内容是 Buffer、字符串或流,也可以在发送时从本地 path 读取。内容类型由文件名推导,非 ASCII 文件名会被编码,使每个邮件客户端都能正确显示。邮件器按邮件客户端的期望组织各部分:logo 与 HTML 相邻,因此只显示文本版本的客户端不会把它列为附件。

警告

绝不要用用户输入构建附件的 path。该路径上的文件会被附上,无论它是什么。URL 会被拒绝,不会去抓取。

调整模板时,你不会想每改一次就下一单。mailer.render() 只渲染邮件类而不发送。一条仅开发环境可用的路由把结果展示在浏览器中。关闭模板缓存后,下次刷新就能看到改过的模板:

notifications/mail-preview.controller.ts
import { Controller, Get, Header } from '@nestjs/common';
import { Mailer } from '@nestjs/mail';
import { OrderConfirmationMail, type OrderConfirmation } from './order-confirmation.mail.js';

const SAMPLE: OrderConfirmation = {
  customer: {
    id: 'sample',
    name: 'Ada Lovelace',
    email: 'ada@example.com',
    // ...
  },
  order: {
    id: '00000000-0000-4000-8000-000000000000',
    number: 1001,
    customerId: 'sample',
    items: [
      { productId: 'salmon-kibble-2kg', name: 'Salmon kibble, 2 kg', quantity: 2, price: 2499 },
      { productId: 'feather-wand', name: 'Feather wand toy', quantity: 1, price: 799 },
    ],
    total: 5797,
    placedAt: '2026-09-22T10:00:00.000Z',
  },
};

@Controller('dev/mail')
export class MailPreviewController {
  constructor(private readonly mailer: Mailer) {}

  /** 用示例数据渲染邮件而不发送:GET /dev/mail/order-confirmation */
  @Get('order-confirmation')
  @Header('content-type', 'text/html; charset=utf-8')
  async orderConfirmation() {
    const message = await this.mailer.render(OrderConfirmationMail, { data: SAMPLE });

    // 浏览器不会解析 cid: 引用;改为把图片内联为 data: URL
    let body = message.html ?? '';
    for (const { cid, contentType, content } of message.attachments) {
      if (cid) {
        body = body.replaceAll(`cid:${cid}`, `data:${contentType};base64,${content.toString('base64')}`);
      }
    }
    return body;
  }
}

render() 返回完成的 MailMessage:主题、HTML 与推导出的文本、附件,以及用于原始消息的 toMime()。这里收件人可选。render() 也接受内联写的消息,例如主题、template 及其 context,以便在没有邮件类时预览模板。只在生产环境之外注册该控制器:

notifications/notifications.module.ts
@Module({
  // 预览路由用示例数据渲染邮件;生产环境不需要
  controllers: process.env.NODE_ENV === 'production' ? [] : [MailPreviewController],
  providers: [OrderConfirmationMail, InvoicePdf],
})
export class NotificationsModule {}

在订单提交后发送

编写订单确认邮件在请求内、订单提交之后发送。那里有三处问题:

  • 提交与发送之间崩溃会丢邮件。 恰好在错误时刻重启进程的部署,会让一笔已付款订单没有确认信。
  • 邮件服务器故障会让一个本已成功的请求失败。 订单已保存,顾客却看到 500,可能再下一单。
  • 顾客要等邮件服务器。 一次 SMTP 交互要几百毫秒,慢服务器会把请求一起拖住。

这是 outbox 教程中的双写问题,outbox(@nestjs/outbox,在该教程中安装与设置)能解决它。订单与一条 order.placed 消息在同一事务中提交,中继把消息交给负责发信的处理器。发送失败时,中继按退避重试,并始终失败的消息移入死信表。outbox 通过其存储 PostgresOutboxStore(来自 @nestjs/outbox/postgres)把消息保存在应用的 PostgreSQL 数据库中,与订单相邻,使用 @nestjs/drizzle 注册的那个数据库。存储在应用启动时于独立 schema 中建表;outbox 教程的把消息保存在你的数据库中介绍了这些表以及生产环境的迁移方式。

本节展示两次订单事务:先是 Drizzle(教程的路径),然后在本节末尾的「使用 TypeORM」中给出同一事务在 TypeORM 应用中的写法。二者取其一。

注册 OutboxModule,并把存储注册为根模块的提供者:一个注入 Drizzle 数据库与 OutboxStorage 注册表的工厂,存储会把自己注册进去。没有它,outbox 会把消息留在内存中,重启即丢:

app.module.ts
@Module({
  imports: [
    // ...
    OutboxModule.forRootAsync({
      useFactory: () => ({
        relay: { enabled: process.env.OUTBOX_RELAY !== 'off' },
        // 邮件服务器短暂宕机也不会丢确认信
        retry: { attempts: 10, backoff: { delay: '10s', maxDelay: '10m' } },
      }),
    }),
    // ...
  ],
  providers: [
    {
      // 消息与收件箱记录在你的数据库中,位于独立 schema(nest_outbox)
      provide: PostgresOutboxStore,
      inject: [getDrizzleToken(), OutboxStorage],
      useFactory: (db: Database, outboxStorage: OutboxStorage) =>
        new PostgresOutboxStore({ executor: fromDrizzle(db) }, outboxStorage),
    },
  ],
})
export class AppModule {}

OrdersService 用 Drizzle 的 tx 添加消息而不是发信,因此消息随订单一起提交或回滚:

orders/orders.service.ts
async placeOrder({ customerId, items }: PlaceOrderDto): Promise<Order> {
  if (!(await this.customersRepository.findById(customerId))) {
    throw new BadRequestException(`Unknown customer "${customerId}"`);
  }
  if (!items?.length) {
    throw new BadRequestException('An order needs at least one item');
  }

  const order = await this.db.transaction(async (tx) => {
    const order = await this.insertOrder(tx, customerId, items);
    // 同一事务:只有订单提交,确认邮件才会入队
    await this.outbox.add(tx, { topic: 'order.placed', payload: order });
    return order;
  });

  this.outbox.notify(); // 立即发送,不等下一次轮询
  return order;
}

处理器负责发信:

notifications/order-mails.handler.ts
import { Injectable } from '@nestjs/common';
import { MailError, Mailer } from '@nestjs/mail';
import { NonRetryableMessageError, OnOutboxMessage, type OutboxHandlerContext } from '@nestjs/outbox';
import { CustomersRepository } from '../customers/customers.repository.js';
import type { Order } from '../orders/order.js';
import { OrderConfirmationMail } from './order-confirmation.mail.js';

@Injectable()
export class OrderMailsHandler {
  constructor(
    private readonly mailer: Mailer,
    private readonly customersRepository: CustomersRepository,
  ) {}

  // 在订单提交后运行。收件箱会跳过该消费者已处理过的消息。
  @OnOutboxMessage('order.placed', { consumer: 'order-confirmation-mail' })
  async sendConfirmation(order: Order, { message, signal }: OutboxHandlerContext) {
    const customer = await this.customersRepository.findById(order.customerId);
    if (!customer) {
      throw new NonRetryableMessageError(`Customer ${order.customerId} not found`);
    }

    try {
      await this.mailer.send(OrderConfirmationMail, {
        to: { name: customer.name, address: customer.email },
        data: { order, customer },
        // 经 SMTP 时,该消息的重投会沿用同一个 Message-ID;Resend 会把它当作
        // Idempotency-Key 并拒绝重复
        idempotencyKey: message.id,
        signal,
        // outbox 用自己的退避重试,并把始终失败的移入死信
        retry: false,
      });
    } catch (error) {
      // 被拒绝的地址或发件人以后也不会被接受:立即死信
      if (error instanceof MailError && error.permanent) {
        throw new NonRetryableMessageError(error.message, { cause: error });
      }
      throw error;
    }
  }
}

在 NotificationsModule 中注册处理器,并从 CustomersModule 导入仓储:

notifications/notifications.module.ts
@Module({
  imports: [CustomersModule],
  // 预览路由用示例数据渲染邮件;生产环境不需要
  controllers: process.env.NODE_ENV === 'production' ? [] : [MailPreviewController],
  providers: [OrderConfirmationMail, InvoicePdf, OrderMailsHandler],
})
export class NotificationsModule {}

send() 调用的每个选项都有职责:

  • idempotencyKey。 outbox 至少投递一次:中继在发送后、记录前崩溃,就会再发一次。该键在这些投递之间标识同一封邮件。Message-ID 请求头由它派生,因此在 SMTP 上重复投递携带相同 id,Gmail 等接收方会据此丢弃。ResendTransport 把该键作为 Resend 的 Idempotency-Key,Resend 在 24 小时内拒绝重复。Postmark、SendGrid 和 SES 自行分配 Message-ID,也没有幂等键,因此用它们时重投可能让顾客收到两次。
  • signal。 处理器超过 publishTimeout 时,中继会中止它。邮件器会中断 SMTP 交互或 HTTP 请求。
  • retry: false。 邮件器默认对瞬时故障重试三次并退避。这里 outbox 已按分钟级退避重试,因此邮件器每次投递只尝试一次。两层都重试会成倍放大。

该包抛出的每个错误都继承 MailError,其 permanent 标志说明再次发送同一消息能否成功。SMTP 的 4xx 回复(灰名单、邮箱已满)、HTTP 提供方的 429、超时或连接中断都是瞬时的:处理器重新抛出,outbox 会重试。5xx 回复(如 550 5.1.1 User unknown)是永久的:处理器抛出 NonRetryableMessageError,outbox 立即死信,而不是再试十次。

当 SMTP 拒绝多个收件人中的一个时,消息发送前事务会被重置,因此错误总是意味着没人收到,outbox 的重试不会投递两次。唯一例外:消息已传输、服务器尚未应答时连接断开。邮件器无法得知服务器是否保留了它,会报告瞬时错误,重试会用相同的 Message-ID 再发一次。

使用 TypeORM。 同一订单事务在 TypeORM 应用中的写法。教程仍以 Drizzle 为路径:用这段代码替代上面的 Drizzle 代码,而不是并列使用。outbox 通过同一个存储、在 TypeORM 的数据源上保存消息,如 outbox 教程的把消息保存在你的数据库中所示。示例应用把这一版放在 src/typeorm,与教程的 Drizzle 代码相邻,顾客、商品与订单都是实体。

TypeOrmModule 在根模块中取代 DrizzleModule,使用与 TypeORM CLI 共享的选项,存储的工厂通过 fromTypeOrm() 注入其 DataSource:

typeorm/app.module.ts
@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      // CLI 使用的实体与迁移;部署时执行迁移(`migration:run`)
      useFactory: () => ({ ...dataSourceOptions, url: process.env.DATABASE_URL }),
    }),
    // ...
    OutboxModule.forRootAsync({
      useFactory: () => ({
        relay: { enabled: process.env.OUTBOX_RELAY !== 'off' },
        // 邮件服务器短暂宕机也不会丢确认信
        retry: { attempts: 10, backoff: { delay: '10s', maxDelay: '10m' } },
      }),
    }),
    // ...
  ],
  providers: [
    {
      // 消息与收件箱记录在你的数据库中,位于独立 schema(nest_outbox)
      provide: PostgresOutboxStore,
      inject: [DataSource, OutboxStorage],
      useFactory: (dataSource: DataSource, outboxStorage: OutboxStorage) =>
        new PostgresOutboxStore({ executor: fromTypeOrm(dataSource) }, outboxStorage),
    },
  ],
})
export class AppModule {}

OrdersService 用数据源开启事务,并把事务的实体管理器传给 outbox.add(),与自己的写入并列。outbox 的类型参数是 TypeORM 的 EntityManager:

typeorm/orders.service.ts
@Injectable()
export class OrdersService {
  constructor(
    private readonly dataSource: DataSource,
    private readonly customersRepository: CustomersRepository,
    private readonly outbox: Outbox<EntityManager>,
  ) {}

  async placeOrder({ customerId, items }: PlaceOrderDto): Promise<Order> {
    // ... 检查顾客与商品,与 Drizzle 版本相同

    const order = await this.dataSource.transaction(async (manager) => {
      const order = await this.insertOrder(manager, customerId, items);
      // 事务的 EntityManager:只有订单提交,确认邮件才会入队
      await this.outbox.add(manager, { topic: 'order.placed', payload: order });
      return order;
    });

    this.outbox.notify(); // 立即发送,不等下一次轮询
    return order;
  }

  private async insertOrder(manager: EntityManager, customerId: string, items: PlaceOrderDto['items']): Promise<Order> {
    const found = await manager.findBy(ProductEntity, { id: In(items.map((item) => item.productId)) });
    // ... 计算行价与总额,与 Drizzle 版本相同
    // 数据库用序列给订单编号:1001、1002……
    const { generatedMaps } = await manager.insert(OrderEntity, { id, customerId, items: lines, total, placedAt });
    const { number } = generatedMaps[0] as Pick<OrderEntity, 'number'>;
    return { id, number, customerId, items: lines, total, placedAt: placedAt.toISOString() };
  }
}

OrderEntity 把 number 声明为标识列(generated: 'identity'),因此 manager.insert() 会在 generatedMaps 中返回数据库分配的编号。实体无法声明序列起点,因此示例的种子迁移把它重置为 1001,与它插入的顾客和商品一起。处理器与 NotificationsModule 保持不变;CustomersRepository 用 TypeORM 读取顾客,与应用其余部分一致。

生产环境发送

开发环境写文件,写到容器被替换时就会丢失的本地磁盘;生产环境需要真正的传输层。从环境中选择,让同一份构建到处运行:

mail-transport.ts
import { FileMailTransport, ResendTransport, SmtpTransport, type MailTransport } from '@nestjs/mail';
import { readFileSync } from 'node:fs';

/**
 * 当前环境的传输层:开发用 `file`(默认),生产用 `smtp` 或 `resend`。
 * 缺少设置会在启动时失败,并指明变量名。
 */
export function mailTransport(env: NodeJS.ProcessEnv = process.env): MailTransport {
  switch (env.MAIL_TRANSPORT ?? 'file') {
    case 'file':
      return new FileMailTransport({ directory: env.MAIL_DIRECTORY ?? 'var/mail' });
    case 'smtp':
      return new SmtpTransport({
        url: required(env, 'SMTP_URL'), // smtp://user:password@smtp.example.com:587
        pool: true,
        // 私有 CA,例如公司网络内的中继
        ...(env.SMTP_CA_FILE && { tls: { ca: readFileSync(env.SMTP_CA_FILE) } }),
      });
    case 'resend':
      return new ResendTransport({ apiKey: required(env, 'RESEND_API_KEY') });
    default:
      throw new Error(`MAIL_TRANSPORT must be "file", "smtp" or "resend" (got "${env.MAIL_TRANSPORT}")`);
  }
}

function required(env: NodeJS.ProcessEnv, name: string): string {
  const value = env[name];
  if (!value) {
    throw new Error(`${name} is required when MAIL_TRANSPORT is "${env.MAIL_TRANSPORT}"`);
  }
  return value;
}

在 forRootAsync() 中构建传输层。工厂在启动时运行,因此 MAIL_TRANSPORT 写错或缺少 SMTP_URL 都会在那里终止应用,而不是等第一封邮件失败:

app.module.ts
MailModule.forRootAsync({
  // 在启动时运行:MAIL_TRANSPORT 有误或缺少 SMTP_URL 会当场终止应用
  useFactory: () => ({
    transport: mailTransport(),
    templates: new FileTemplateEngine({
      dir: join(import.meta.dirname, 'mail/templates'),
      layout: 'layout',
      cache: process.env.NODE_ENV === 'production',
    }),
    from: process.env.MAIL_FROM ?? 'Orders <orders@example.com>',
  }),
}),

SMTP。 SmtpTransport 自行实现 SMTP,基于 node:net 与 node:tls:

  • 加密。 在 587 端口用 STARTTLS 升级,不提供 STARTTLS 的服务器会被拒绝,而不是明文发送。startTls: 'opportunistic'(localhost 的默认值)只在服务器提供时升级,'never' 保持明文,适用于可信网络内的中继。在 465 端口(smtps://)从第一个字节起就是 TLS。证书按主机名校验;tls.ca 可添加私有 CA。凭据绝不会经未加密连接发送,localhost 除外。
  • 身份验证。 使用服务器提供的 AUTH PLAIN 或 LOGIN,authMethod 可强制其一。对 Gmail 和 Microsoft 365,把 OAuth 访问令牌作为 auth 中的 accessToken 传入以使用 XOAUTH2。OAuth 访问令牌会过期(通常一小时),因此 accessToken 也可以是返回令牌或其 promise 的函数:每次新建连接时调用,可获取新令牌。name 设置传输层在 EHLO 中自我介绍的名字;默认是机器的主机名(若为完全限定名),否则是其 IP 地址。
  • 连接池。 pool: true 保持最多五个连接并复用,而不是每封邮件都做 TCP 与 TLS 握手。传对象可设上限:maxConnections(默认 5,超出的发送等待空闲连接)、maxMessages(默认 100,之后替换连接)和 idleTimeout(默认 '30s',之后关闭空闲连接)。应用关闭时每个连接都会 QUIT。
  • 回复。 4xx 回复是瞬时的 MailSmtpError,5xx 是永久的。两者都带有回复 code、增强码(如 5.1.1)和服务器文本。

当你的 SMTP 服务器不签名时,可用 dkim 自行签名,提供域名(domainName)、选择器(keySelector)和私钥(privateKey,PEM 或 KeyObject)。RSA 密钥用 rsa-sha256 签名,Ed25519 用 ed25519-sha256(RFC 8463);并非所有接收方都验证 Ed25519 签名,且传输层只用一个密钥签名,因此除非你确知收件方的服务器支持,RSA 是稳妥选择。签名覆盖 From、Reply-To、To、Cc、Subject、Date、Message-ID 以及 MIME 头,外加消息的自定义头;dkim.headers 可替换该列表。From 始终被签名,且列出次数比消息中出现的次数多一,因此在签名之后追加的第二个 From 会破坏签名。HTTP 提供方会用你已验证的域名自行签名。

HTTP 提供方。 ResendTransport、PostmarkTransport、SendGridTransport 和 SesTransport 用 fetch 调用各家 API,无需 SDK。fetch 选项可替换全局实现,用于走代理或在测试中打桩。SesTransport 用 AWS Signature Version 4 签名请求,并接受 AWS SDK 的凭据提供者(如实例角色)作为 credentials。四者中只有 Resend 支持幂等键。Resend 与 SendGrid 至少需要一个 to 收件人:只有 cc 或 bcc 的邮件会在请求前以 MailMessageError 失败。

国际化地址。 含非 ASCII 字符的域名(zoë@kočka.example)会对所有传输层转换成 ASCII 形式(IDNA,xn--...),因此无需服务器支持。@ 之前的非 ASCII 本地部分无法转换:经 SMTP 需要服务器的 SMTPUTF8 扩展。SmtpTransport 在服务器提供时使用 SMTPUTF8,否则在发送任何内容前以永久的 MailConnectionError 失败:The SMTP server ... doesn't support SMTPUTF8, which an address with non-ASCII characters needs。HTTP 提供方原样收到地址,是否接受取决于提供方。

在 main.ts 中使用 app.enableShutdownHooks(),让部署时中继发送完在途邮件,并在之后关闭 SMTP 连接池。

用顾客的语言发送

商店以英语和波兰语销售。顾客注册时选择语言,customers 表把它存在 locale 列:en 或 pl。邮件器把每次发送的语言环境交给模板引擎,由它挑选模板。

翻译模板:在英文版旁添加 order-confirmation.pl.html。

mail/templates/order-confirmation.pl.html
<p>Cześć {{ customer.name }},</p>
<p>dziękujemy za zamówienie! Właśnie je pakujemy.</p>
<table>
  <tr><th>Produkt</th><th>Ilość</th><th>Cena</th></tr>
  {{#each items}}
  <tr>
    <td>{{ name }}</td>
    <td>{{ quantity }}</td>
    <td>{{ price }}</td>
  </tr>
  {{/each}}
</table>
<p><strong>Razem: {{ total }}</strong></p>
<p><a href="{{ orderUrl }}">Zobacz zamówienie</a></p>
<p>Fakturę znajdziesz w załączniku.</p>

对语言环境 pl,FileTemplateEngine 渲染 order-confirmation.pl.html;其他语言环境或没有语言环境时渲染 order-confirmation.html。区域语言环境会先试自身,再试其语言:对 pt-BR,引擎先找 order-confirmation.pt-BR.html,再找 order-confirmation.pt.html。局部模板与布局也按同样方式查找,因此布局保持共享,波兰语签名是它自己的局部模板:

mail/templates/partials/signature.pl.html
<p>Zespół obsługi klienta</p>

邮件的文案是散文,因此按文件翻译:译者看到整封邮件,直接写波兰语句子,而不是逐个填键。邮件类计算的内容仍取决于语言环境:主题、发票文件名和价格。它们来自 @nestjs/i18n,国际化一章有深入介绍。为邮件添加词条目录,每种语言一个:

i18n/en/mail.json
{
  "orderConfirmation": {
    "subject": "Your order #{number}",
    "invoiceFile": "invoice-{number}.pdf"
  }
}
i18n/pl/mail.json
{
  "orderConfirmation": {
    "subject": "Twoje zamówienie #{number}",
    "invoiceFile": "faktura-{number}.pdf"
  }
}

注册词条目录的形状,使键在编译期受检查,并在 MailModule 旁注册 I18nModule:

i18n/translations.ts
import type mail from './en/mail.json';

export interface Translations {
  mail: typeof mail;
}

declare module '@nestjs/i18n' {
  interface I18nTypes {
    translations: Translations;
  }
}
app.module.ts
@Module({
  imports: [
    // ...
    I18nModule.forRoot({
      defaultLocale: 'en',
      supportedLocales: ['en', 'pl'],
      loader: new JsonI18nLoader({ path: join(import.meta.dirname, 'i18n') }),
    }),
    MailModule.forRootAsync({
      // ...
    }),
    // ...
  ],
})
export class AppModule {}

也要把词条目录加入 nest-cli.json 的资源(i18n/**/*.json),如国际化一章所示。

邮件类是提供者,因此在发票渲染器旁注入 I18nService。render() 的第二个参数是渲染上下文,其 locale 就是传给 send() 的那个,也是邮件器交给模板引擎的那个。其 to 持有解析后的收件人,没有收件人的预览则为空:

notifications/order-confirmation.mail.ts
type Key = keyof Translations['mail']['orderConfirmation'];

const SHOP_URL = process.env.SHOP_URL ?? 'https://shop.example.com';
const LOGO = join(import.meta.dirname, 'assets/logo.png');

@Injectable()
export class OrderConfirmationMail implements Mailable<OrderConfirmation> {
  constructor(
    private readonly i18nService: I18nService,
    private readonly invoicePdf: InvoicePdf,
  ) {}

  render({ order, customer }: OrderConfirmation, { locale }: MailRenderContext) {
    // 邮件在顾客请求之外发送,因此语言环境总是显式传入
    const t = (key: Key, args?: Record<string, unknown>) =>
      this.i18nService.t(`mail.orderConfirmation.${key}`, { locale, args });
    const price = (cents: number) =>
      this.i18nService.formatNumber(cents / 100, { locale, style: 'currency', currency: 'USD' });
    return {
      subject: t('subject', { number: order.number }),
      // 波兰语用 order-confirmation.pl.html,否则 order-confirmation.html
      template: 'order-confirmation',
      // ...
      attachments: [
        // 内联:布局中的 <img> 通过 cid 引用它
        { cid: 'logo@example.com', path: LOGO },
        { filename: t('invoiceFile', { number: order.number }), content: this.invoicePdf.render(order, customer) },
      ],
    };
  }
}

上下文不变:同一批值填充任一模板。Key 是 keyof Translations['mail']['orderConfirmation'],因此拼错的键是编译错误。价格按语言环境格式化:英语为 $25.98,波兰语为 25,98 USD。发票文件名来自词条目录:invoice-1001.pdf 或 faktura-1001.pdf。

警告

显式传入语言环境。I18nService 会退回当前请求的语言环境,而邮件常在收件人的请求之外发送:例如这里的 outbox 处理器,或由他人(如管理员)发起的请求。那个请求的语言环境是错的。

outbox 处理器在发送时传入顾客的语言环境:

notifications/order-mails.handler.ts
await this.mailer.send(OrderConfirmationMail, {
  to: { name: customer.name, address: customer.email },
  data: { order, customer },
  locale: customer.locale,
  // ...
});

波兰语的主题或收件人姓名不能原样进入邮件头:请求头是 ASCII。邮件器把非 ASCII 头文本编码为 RFC 2047 encoded-word,例如 =?UTF-8?Q?Twoje_zam=C3=B3wienie_=231001?=,正文则用 quoted-printable,因此每台服务器都能原样传递,邮件客户端显示 Twoje zamówienie #1001。

预览从查询串取语言,因此两种版本都能在浏览器中检查:

notifications/mail-preview.controller.ts
/** 用示例数据渲染邮件而不发送:GET /dev/mail/order-confirmation?locale=pl */
@Get('order-confirmation')
@Header('content-type', 'text/html; charset=utf-8')
async orderConfirmation(@Query('locale') locale = 'en') {
  const message = await this.mailer.render(OrderConfirmationMail, { data: SAMPLE, locale });
  // ...
}

使用其他模板引擎

FileTemplateEngine 实现 MailTemplateEngine,这是一个只有一个方法的抽象类:render() 接收模板名、上下文和语言环境,返回 HTML,或带 html 与 text 的对象,或二者的 promise。继承它即可用 Handlebars、EJS 或其他引擎渲染。下面是一个渲染 .hbs 文件中 Handlebars 模板的引擎:

mail/handlebars-template.engine.ts
import { MailTemplateEngine, MailTemplateError, type MailTemplateRenderOptions } from '@nestjs/mail';
import Handlebars from 'handlebars';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';

const TEMPLATES = join(import.meta.dirname, 'templates');

/** 用 Handlebars 渲染 order-confirmation.pl.hbs,否则 order-confirmation.hbs。 */
export class HandlebarsTemplateEngine extends MailTemplateEngine {
  private readonly templates = new Map<string, ReturnType<typeof Handlebars.compile> | undefined>();

  async render(name: string, context: object, { locale }: MailTemplateRenderOptions) {
    // 进入文件名的只有语言代码,绝不是 locale 持有的任意内容
    const localized = locale && /^[a-z]{2}$/.test(locale) ? [`${name}.${locale}.hbs`] : [];
    for (const file of [...localized, `${name}.hbs`]) {
      const template = await this.load(file);
      if (template) {
        return template(context);
      }
    }
    throw new MailTemplateError(`No template "${name}" in ${TEMPLATES}`, { template: name });
  }

  private async load(file: string) {
    if (!this.templates.has(file)) {
      const source = await readFile(join(TEMPLATES, file), 'utf8').catch(() => undefined);
      // compat:普通路径会回退到外层上下文,与 FileTemplateEngine 一致
      this.templates.set(file, source === undefined ? undefined : Handlebars.compile(source, { compat: true }));
    }
    return this.templates.get(file);
  }
}

把它作为 templates 传入以替代 FileTemplateEngine:实例,或由 Nest 实例化的类(因此可注入配置或其他提供者)。与传输层一样,类放在 forRootAsync() 顶层、useFactory 旁边,工厂返回实例。

邮件器按引擎返回的内容原样发送 HTML,因此转义由引擎负责:Handlebars 会转义双花括号的值,与 FileTemplateEngine 一样。compat: true 让 #each 内的名称回退到外层上下文,因此本教程的模板在 Handlebars 下可原样渲染。Handlebars 不认识 partials/ 目录和布局:请用 Handlebars.registerPartial() 注册局部模板,并自行把布局套在邮件外面。对 MJML,请在返回 HTML 前用 mjml2html() 转换渲染后的 MJML。模板缺失或损坏时抛出 MailTemplateError:它是永久错误,outbox 会把该邮件移入死信而不是重试。

编写自己的传输层

对包里没有传输层的服务,继承 MailTransport。其 send() 接收完成后的消息,在服务方接受后决议。下面是一个 Mailgun 传输层,它的 messages.mime 端点接收 MIME 形式的消息,正如 SesTransport 发给 SES 那样:

mail/mailgun.transport.ts
import {
  MailProviderError,
  MailTransport,
  type MailMessage,
  type MailTransportResult,
  type MailTransportSendOptions,
} from '@nestjs/mail';

export interface MailgunTransportOptions {
  domain: string;
  apiKey: string;
  /** 域名位于 EU 区域时用 `https://api.eu.mailgun.net`。 */
  baseUrl?: string;
}

/** 通过 Mailgun 的 `messages.mime` 端点发送完成后的 MIME 消息。 */
export class MailgunTransport extends MailTransport {
  readonly #apiKey: string;
  private readonly url: string;

  constructor({ domain, apiKey, baseUrl = 'https://api.mailgun.net' }: MailgunTransportOptions) {
    super();
    this.#apiKey = apiKey;
    this.url = `${baseUrl}/v3/${encodeURIComponent(domain)}/messages.mime`;
  }

  async send(message: MailMessage, { signal }: MailTransportSendOptions): Promise<MailTransportResult> {
    const form = new FormData();
    // 信封列出每个收件人;MIME 消息不含 Bcc
    form.append('to', message.envelope.to.join(','));
    form.append('message', new Blob([new Uint8Array(message.toMime())]), 'message.eml');

    // 中止会以 signal.reason 拒绝;网络错误是瞬时的,邮件器会重试
    const response = await fetch(this.url, {
      method: 'POST',
      headers: { authorization: `Basic ${Buffer.from(`api:${this.#apiKey}`).toString('base64')}` },
      body: form,
      signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
    });

    if (!response.ok) {
      const retryAfter = Number(response.headers.get('retry-after'));
      // 除 408、409、429 外的 4xx 是永久的:那些与 5xx 会重试
      throw new MailProviderError({
        provider: 'mailgun',
        status: response.status,
        detail: await response.text(),
        ...(retryAfter > 0 && { retryAfterMs: retryAfter * 1_000 }),
      });
    }

    const { id } = (await response.json()) as { id?: string };
    return { accepted: message.envelope.to, providerMessageId: id };
  }
}

像内置传输层一样,把实例作为 transport 传入。send(message, options) 收到:

  • message。 一个 MailMessage,已校验并冻结:from、to、cc、bcc、replyTo、subject、html、text、attachments、headers 和 messageId。envelope 持有 SMTP 信封,每个收件人只出现一次(含 Bcc),toMime() 返回不含 Bcc 头的 MIME 消息。每次尝试都是同一个对象。
  • signal。 调用方取消发送时中止,例如 outbox 中继在处理器超时后。请停止请求并以 signal.reason 拒绝;邮件器不会重试中止。
  • idempotencyKey。 调用方的键,每次尝试与每次重投都相同。把它发给会去重的提供方,如 ResendTransport 所做;Message-ID 已由它派生。
  • attempt。 首次尝试为 1,第一次重试为 2。

它决议为 accepted(提供方接受的收件人,省略时视为全部)、providerMessageId 和 response,而邮件器的 send() 又会决议为这些。

抛出什么决定邮件器是否重试。请抛出 MailError,其 permanent 说明再次发送同一消息能否成功:HTTP API 拒绝时抛 MailProviderError(除 408、409、429 之外的 4xx 为永久,除非你自己传 permanent),请求失败或过慢时抛 MailConnectionError 与 MailTimeoutError。其他任何错误都算瞬时,除非它带 permanent: true 或 4xx 的 status,因此 fetch 的网络错误会被重试。带 retryAfterMs 的错误会让邮件器在下次尝试前至少等待那么久,上限为 maxDelay。

持有连接或客户端的中继层应实现 close(),它在应用关闭时、在途发送完成后运行。

试一试

应用迁移,它还会添加两位顾客和四件商品:

$ export DATABASE_URL=postgres://localhost:5432/store
$ npx drizzle-kit migrate

用默认配置启动应用:文件传输层,中继运行。为 Ada 下一单:

$ curl -X POST localhost:3000/orders \
    -H 'Content-Type: application/json' \
    -d '{"customerId":"ada","items":[{"productId":"salmon-kibble-2kg","quantity":2},{"productId":"feather-wand","quantity":1}]}'
{"id":"fd2bfc1c-db5c-455c-8876-bf7331a1029c","number":1001,"customerId":"ada","items":[{"productId":"salmon-kibble-2kg","name":"Salmon kibble, 2 kg","quantity":2,"price":2499},{"productId":"feather-wand","name":"Feather wand toy","quantity":1,"price":799}],"total":5797,"placedAt":"2026-09-25T10:59:00.173Z"}

响应在任何邮件发出之前就返回。稍后,中继的处理器渲染邮件,文件传输层写出它:

[Nest] 37252  - 09/25/2026, 12:59:00 PM     LOG [FileMailTransport] "Your order #1001" to ada@example.com written to var/mail/2026-09-25T10-59-00-199Z--LtIZd5B_AiZek3-x8nOt88YfUYjgkZi-42ff80.eml

该文件就是 SMTP 将传输的消息本身。其请求头与文本部分:

$ head -33 var/mail/*.eml
From: Orders <orders@example.com>
To: Ada Lovelace <ada@example.com>
Subject: Your order #1001
Date: Fri, 25 Sep 2026 10:59:00 +0000
Message-ID: <-LtIZd5B_AiZek3-x8nOt88YfUYjgkZi@example.com>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="=_bTCd1MQ5LoxTNFNN0nLRwu8d"

--=_bTCd1MQ5LoxTNFNN0nLRwu8d
Content-Type: multipart/alternative; boundary="=_9HVDyVBGuLsAaijTpu4Y2_XU"

--=_9HVDyVBGuLsAaijTpu4Y2_XU
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

Hi Ada Lovelace,

thank you for your order! We are packing it now.

Product Qty Price
Salmon kibble, 2 kg 2 $49.98
Feather wand toy 1 $7.99

Total: $57.97

View your order (https://shop.example.com/orders/fd2bfc1c-db5c-455c-8876-bf=
7331a1029c)

Your invoice is attached.

The customer care team
--=_9HVDyVBGuLsAaijTpu4Y2_XU
Content-Type: multipart/related; boundary="=_u7PgKDXrb-x3mIz35ZArIBAa"

几点值得注意:

  • Message-ID 由 outbox 消息的 id 派生,不是随机的。重投会携带同一个。
  • 文本部分由 HTML 推导,链接被完整写出。
  • 正文是 quoted-printable,让每行都短到任何邮件服务器都能接受:链接首行末尾的 = 会与下一行拼接。

接着是 HTML、logo 和发票:

$ grep -E '^Content-(Type|Disposition|ID):' var/mail/*.eml | tail -5
Content-Type: image/png; name="logo.png"
Content-Disposition: inline; filename="logo.png"
Content-ID: <logo@example.com>
Content-Type: application/pdf; name="invoice-1001.pdf"
Content-Disposition: attachment; filename="invoice-1001.pdf"

用邮件客户端打开该文件即可看到渲染后的邮件。要调整模板,请在浏览器中打开预览。响应就是邮件的 HTML——模板套在布局中,logo 以 data: URL 内联(此处有删减):

$ curl localhost:3000/dev/mail/order-confirmation
<!DOCTYPE html>
<html>
<body>
<p><img src="data:image/png;base64,…" alt="Logo" width="120" height="32"></p>
<p>Hi Ada Lovelace,</p>
<p>thank you for your order! We are packing it now.</p>
<table>
  <tr><th>Product</th><th>Qty</th><th>Price</th></tr>
  <tr>
    <td>Salmon kibble, 2 kg</td>
    <td>2</td>
    <td>$49.98</td>
  </tr>
  <tr>
    <td>Feather wand toy</td>
    <td>1</td>
    <td>$7.99</td>
  </tr>
</table>
<p><strong>Total: $57.97</strong></p>
<p><a href="https://shop.example.com/orders/00000000-0000-4000-8000-000000000000">View your order</a></p>
<p>Your invoice is attached.</p>

<p>The customer care team</p>
</body>
</html>

接着,订一件不存在的商品:

$ curl -X POST localhost:3000/orders \
    -H 'Content-Type: application/json' \
    -d '{"customerId":"ada","items":[{"productId":"salmon-kibble-2kg","quantity":1},{"productId":"catnip-mouse","quantity":1}]}'
{"message":"Unknown product \"catnip-mouse\"","error":"Bad Request","statusCode":400}

事务回滚,order.placed 消息随之回滚,不会写出任何邮件。

最后,看看顾客的语言如何生效。为注册时选择波兰语的 Zofia 下一单:

$ curl -X POST localhost:3000/orders \
    -H 'Content-Type: application/json' \
    -d '{"customerId":"zofia","items":[{"productId":"feather-wand","quantity":1}]}'
{"id":"7fa5ce1f-9ef3-49b0-8de9-a2d98056c299","number":1002,"customerId":"zofia","items":[{"productId":"feather-wand","name":"Feather wand toy","quantity":1,"price":799}],"total":799,"placedAt":"2026-09-25T10:59:00.424Z"}
[Nest] 37252  - 09/25/2026, 12:59:00 PM     LOG [FileMailTransport] "Twoje zamówienie #1002" to zofia@example.com written to var/mail/2026-09-25T10-59-00-453Z-GnMdyKUxVa0FRBJ6wZ2k5snIWsdQmwC2-697a51.eml

正文来自 order-confirmation.pl.html。波兰语主题与 Zofia 的名字以 encoded-word 形式进入文件,她的发票是 faktura-1002.pdf:

$ head -3 var/mail/2026-09-25T10-59-00-453Z-GnMdyKUxVa0FRBJ6wZ2k5snIWsdQmwC2-697a51.eml
From: Orders <orders@example.com>
To: =?UTF-8?Q?Zofia_W=C3=B3jcik?= <zofia@example.com>
Subject: =?UTF-8?Q?Twoje_zam=C3=B3wienie_=231002?=

测试

把传输层换成 InMemoryMailTransport。它会保留收到的每封邮件,并提供查找与读取的辅助方法:

test/order-confirmation.e2e-spec.ts
import { PGlite } from '@electric-sql/pglite';
import { getDrizzleToken } from '@nestjs/drizzle';
import { InMemoryMailTransport, MailSmtpError, MailTransport } from '@nestjs/mail';
import { OutboxDeadLetters, OutboxRelay } from '@nestjs/outbox';
import { Test, type TestingModule } from '@nestjs/testing';
import { drizzle } from 'drizzle-orm/pglite';
import { migrate } from 'drizzle-orm/pglite/migrator';
import { fileURLToPath } from 'node:url';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { AppModule } from '../src/app.module.js';
import { OrderConfirmationMail } from '../src/notifications/order-confirmation.mail.js';
import { OrdersService } from '../src/orders/orders.service.js';

describe('Order confirmation mail', () => {
  const client = new PGlite(); // 进程内 PostgreSQL
  const mailbox = new InMemoryMailTransport();
  let moduleRef: TestingModule;
  let orders: OrdersService;
  let relay: OutboxRelay;

  beforeAll(async () => {
    const db = drizzle({ client });
    // 你的迁移:建表,以及预置的顾客与商品。outbox 的存储在 init() 中自建 schema。
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    process.env.OUTBOX_RELAY = 'off'; // 不轮询:由测试驱动中继
    moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(db) // outbox 的存储也跑在它上面
      .overrideProvider(MailTransport)
      .useValue(mailbox)
      .compile();
    await moduleRef.init();
    orders = moduleRef.get(OrdersService);
    relay = moduleRef.get(OutboxRelay);
  });

  afterAll(async () => {
    await moduleRef.close();
    await client.close();
  });

  beforeEach(() => mailbox.clear());

  it('confirms the order with the invoice and a link to it', async () => {
    const order = await orders.placeOrder({ customerId: 'ada', items: [{ productId: 'salmon-kibble-2kg', quantity: 1 }] });
    mailbox.assertNotSent(); // 中继发布已提交的订单之前,什么都没有

    await relay.runOnce();

    const mail = mailbox.assertSent({ to: 'ada@example.com', mail: OrderConfirmationMail });
    expect(mail.subject).toBe(`Your order #${order.number}`);
    expect(mail.attachment(`invoice-${order.number}.pdf`).contentType).toBe('application/pdf');
    expect(mail.link('/orders/').pathname).toBe(`/orders/${order.id}`);
  });

  it('dead-letters a confirmation the mail server refuses', async () => {
    mailbox.failNext(new MailSmtpError('RCPT TO', { code: 550, text: 'User unknown' }));
    await orders.placeOrder({ customerId: 'ada', items: [{ productId: 'salmon-kibble-2kg', quantity: 1 }] });

    await relay.runOnce();

    mailbox.assertNotSent();
    const [deadLetter] = await moduleRef.get(OutboxDeadLetters).list();
    expect(deadLetter).toMatchObject({ topic: 'order.placed', reason: 'rejected' });
  });
});
  • 除网络外一切都是真的。 邮件类用词条目录与发票提供者渲染模板,outbox 与其收件箱真实运行,消息完整构建(含请求头与附件)。只有投递被替换。
  • 数据库是进程内 PostgreSQL。 PGlite(@electric-sql/pglite,开发依赖)运行你的真实迁移,测试用 overrideProvider 把 DrizzleModule 注册的数据库(其标记来自 getDrizzleToken())替换为它,因此仓储与 outbox 存储都用它。无需启动服务器,每个测试文件都有全新的数据库。
  • assertSent() 返回最近一封匹配的邮件,可按收件人(to 匹配 to、cc、bcc)、subject、邮件类或 template,或谓词匹配。没有匹配时抛出错误并列出已发送的内容。assertNotSent()、filter()、find() 和 mails 覆盖其余场景。这些辅助方法抛出普通错误,因此适用于任何测试运行器。
  • link() 返回邮件中第一个包含指定字符串或匹配正则的链接,类型为 URL。对密码重置或魔法链接,这就是整个测试:发出邮件,然后调用 mail.link('/reset-password').searchParams.get('token') 并跟随链接。实体会被解码,因此转义写入查询串的 &amp; 会还原为 &。
  • failNext() 让下一次发送抛出,这里是永久性的 SMTP 错误,用于测试错误路径。
  • raw 是 MIME 形式的消息;mailer.render() 可单独渲染邮件类或模板,用于模板的单元测试。

生产检查清单

  • 为发信域名配置 SPF、DKIM 和 DMARC。HTTP 提供方在域名验证后会用 DKIM 签名;使用 SMTP 时,用 dkim 选项或在中继上签名。
  • 保持 STARTTLS 强制与证书校验开启。中继使用私有 CA 时,传入 tls.ca,而不要关闭校验。
  • 凭据放在环境或密钥库中。传输层把它们保存在私有字段里,错误消息从不包含它们。
  • 事务性邮件在提交后经 outbox 发送,处理器中设 retry: false,outbox 的重试策略按你的提供方可能宕机多久来定。
  • 对可能执行两次的处理器所发的每封邮件,都传 idempotencyKey。
  • 把永久性邮件错误转为死信,并对 dead-lettered outbox 事件告警。被拒绝的地址通常意味着注册时打错字,或邮箱已不存在。
  • 关注 MailEvents,或 nestjs:mail:sent 与 nestjs:mail:failed 诊断通道,以发现投递失败与慢发送。
  • 生产环境用 SmtpTransport 或 HTTP 提供方的传输层发送。FileMailTransport 写本地磁盘,容器重启或被替换时会丢失;LogMailTransport 只写日志:两者都用于开发,InMemoryMailTransport 用于测试。模块在 NODE_ENV=production 下发现它们之一运行时会发出警告。
  • 通过 PostgresOutboxStore 或其他已注册的存储,把 outbox 消息保存在应用数据库中,使排队的邮件随订单提交并能承受重启。没有存储时,outbox 在 NODE_ENV=production 下拒绝启动,存储未执行迁移时同样如此:请在部署时执行迁移,如 outbox 教程所示。
  • 用 CLI 资源把模板发布到 dist,并在生产环境保持模板缓存开启(默认即如此):cache: false 会为每封邮件重读文件。
  • 不要在生产环境注册仅开发的路由,例如预览。
  • 使用 app.enableShutdownHooks(),让部署等待在途邮件并关闭 SMTP 连接。

参考

模块选项

MailModule.forRoot() 接受以下选项,forRootAsync() 工厂返回它们。用 useClass 或 useExisting 代替 useFactory 时,该类实现 MailOptionsFactory,其 createMailOptions() 返回它们。transport、templates、imports 和 isGlobal 在 forRootAsync() 中也放在 useFactory、useClass 或 useExisting 旁边。解析后的选项以 MAIL_MODULE_OPTIONS 标记提供。

选项 类型 默认值 说明
transport MailTransport 实例或类 无(必填) 邮件如何离开应用。类由 Nest 实例化,因此可注入配置。参见生产环境发送。
templates MailTemplateEngine 实例或类 无 渲染指定了 template 的邮件:FileTemplateEngine 或你自己的。类由 Nest 实例化。没有它时,带模板的邮件以 MailTemplateError 失败。
from 地址 无 默认发件人。没有发件人的消息以 MailMessageError 失败。
replyTo 地址或数组 无 默认 Reply-To。
headers Record<string, string> 无 添加到每封邮件。邮件自身的请求头优先。
retry 数字、false 或重试选项 3 次尝试 每次发送的尝试次数,退避从 1s 起翻倍到 30s,完全抖动。false 表示只尝试一次。参见在订单提交后发送。
imports 模块 无 传输层或模板引擎类所注入的导出提供者所在模块。
isGlobal boolean true 全局注册 Mailer、MailEvents、MailTransport 与 MailTemplateEngine。

重试选项为 attempts(总数,含首次)、backoff(带 delay、factor、maxDelay 和 jitter 的对象,或关于尝试序号的函数)以及 retryIf(只能收窄哪些瞬时错误会被重试)。HTTP 提供方以 Retry-After 头应答时(通常是 429 或 503),错误会把它保留为 retryAfterMs,邮件器在下次尝试前至少等待那么久,上限为 maxDelay(使用退避函数时为 30s)。signal 仍会结束等待。SMTP 回复没有 Retry-After,而设了 retry: false 的 outbox 处理器把等待交给 outbox 的退避。

模板引擎

FileTemplateEngine 接受:

选项 类型 默认值 说明
dir string 无(必填) 模板目录,局部模板在其 partials/ 文件夹中。相对路径按工作目录解析。
layout string 无 包裹每封邮件 HTML 的模板,用三花括号把邮件放到 body 处。若有 .txt 版本,则用它包裹文本。
cache boolean true 在内存中保留编译后的模板以及哪些文件存在。false 为每封邮件重读文件,便于开发时看到改动。

template: 'order-confirmation' 搭配语言环境 pt-BR 时,渲染 order-confirmation.pt-BR.html、order-confirmation.pt.html 和 order-confirmation.html 中第一个存在的文件,文本部分同理取同名 .txt(若有)。模板名由字母、数字、- 和 _ 组成,位于以 / 分隔的文件夹中。其他名称以及不是语言标签的语言环境会以 MailTemplateError 失败,因此二者都无法触及 dir 之外的文件。

模板语法

语法是 Handlebars 的子集:

语法 渲染结果
{{ customer.name }} 该值,经 HTML 转义。路径用点号,items.0 是数组第一项。缺失的值渲染为空。在 .txt 模板中为原值。
{{{ body }}} 原样插入的值,用于你自己生成的 HTML。用 html 标签构建的 HTML 在双花括号之间也原样插入。
{{#if paid}} … {{else}} … {{/if}} 值为真时取第一部分,否则取 else 部分(可选)。false、0、空字符串、空列表与缺失值都为假。{{else if pending}} 可再链一个条件。
{{#unless paid}} … {{/unless}} #if 的反面,可带可选的 else 部分。
{{#each items}} … {{else}} … {{/each}} 第一部分对列表的每个元素或对象的每个值各渲染一次;else 部分用于空或缺失的列表。
this, @index, @first, @last, @key 在 #each 内:当前元素、从 0 开始的位置、是否为第一个或最后一个,以及对象的键。元素上不存在的名称会到外层上下文查找。
../number, @root.shop 当前 #each 之外的上下文,以及模板的上下文。
{{> signature}} 局部模板 partials/signature.html(文本模板中为 .txt),使用邮件的语言环境与包含处的上下文。
{{! note }}、{{!-- note --}} 注释,不进入输出。第二种形式可以包含双花括号。
\{{ 字面双花括号。

没有 helper,也没有表达式。值只从上下文自身的属性读取,绝不来自原型,函数不会被调用。双花括号之间的其他内容、永不闭合的块,以及标签内但不在带引号属性值中的双花括号值,都会以 MailTemplateError 失败,错误带 file、line 和 column。

发送选项

mailer.send(MailClass, options) 与 mailer.send(message) 接受:

选项 说明
to、cc、bcc 一个地址或数组。地址是恰好包含一个地址的字符串,或带 name 与 address 的对象。bcc 只进入 SMTP 信封。
data 邮件类的数据,类型来自其 render()。
locale 在渲染上下文中传给 render(),也传给模板引擎,由它挑选模板。参见用顾客的语言发送。
from、replyTo 覆盖模块默认值。
subject、html、text 内联写的消息内容。省略 text 时由 html 推导。
template、context 正文所渲染的模板及其读取的值,替代 html 与 text。邮件类的 render() 也以同样方式返回它们。
attachments 每个附件有 filename、content(Buffer、字符串或流)或本地 path,可选 contentType 与 cid。参见附带发票并预览邮件。
headers 自定义请求头,例如 List-Unsubscribe。
retry 为本次发送覆盖模块的 retry。
signal 停止发送以及尝试之间任何等待的 AbortSignal。
idempotencyKey 在重投之间标识这封邮件。Message-ID 由它派生。

mailer.render(MailClass, options) 与 mailer.render(message) 接受相同选项但不含投递选项,决议为 MailMessage,它记录了自己的 template 与 locale。send() 决议为 messageId、providerMessageId(提供方有时)、accepted(接受的收件人)、response(最终 SMTP 回复)和 attempts。

传输层

传输层 选项 幂等键
SmtpTransport url 或 host、port、secure、startTls(required、opportunistic 或 never;默认 required,localhost 为 opportunistic)、auth(user 配 pass 或 accessToken)、authMethod(PLAIN、LOGIN 或 XOAUTH2)、name、tls、pool、timeouts、dkim(domainName、keySelector、privateKey、headers) 仅派生的 Message-ID
ResendTransport apiKey、baseUrl、timeout、fetch Idempotency-Key,24 小时
PostmarkTransport serverToken、messageStream(默认 outbound)、baseUrl、timeout、fetch 无
SendGridTransport apiKey、baseUrl、timeout、fetch 无
SesTransport region、credentials、configurationSetName、endpoint、timeout、fetch 无
FileMailTransport directory、log 仅开发
LogMailTransport body、logger 仅开发
InMemoryMailTransport 无 仅测试,参见测试

InMemoryMailTransport.mails 按最旧在前列出收到的每封邮件,类型为 SentMail,filter()、find() 与 assertSent() 也返回它。SentMail 有消息的 messageId、from、to、cc、bcc、subject、html、text、attachments、headers、mail(邮件类)、template 和 locale,另有 sentAt(传输层收到的时间)、raw(MIME 源)、links(所有链接,先来自 HTML,再补只有文本部分才有的)、link()、attachment() 和 message(MailMessage 本身)。clear() 会清空它们。

pool: true 时,SmtpTransport 最多保持 5 个连接,每个连接最多发送 100 条消息,空闲 30 秒后关闭;用带 maxConnections、maxMessages 和 idleTimeout 的对象作为 pool 可改变这些限制。其默认超时为:连接 30s、问候 30s、每条命令 1m、数据 5m。HTTP 提供方每个请求 30s 超时。

事件

MailEvents.events$ 在每次发送(含重试)后发出一个事件。每个事件也会发布到 node:diagnostics_channel 通道。

事件类型 通道 触发时机 负载
sent nestjs:mail:sent 传输层接受了消息。 messageId、mail、recipients、subject、transport、attempts、durationMs、providerMessageId
failed nestjs:mail:failed 发送在重试后失败,或其 signal 在首次尝试前中止(attempts 为 0)。 相同字段但无 providerMessageId,另加 error 与 permanent

校验失败的消息在任何事件之前抛出。

错误

每个错误都继承 MailError,它带有 permanent(再次发送同一消息是否一定失败)和 code(SMTP 回复码或提供方的 HTTP 状态)。邮件器只重试非永久错误。参见在订单提交后发送。

错误 触发时机 是否永久
MailMessageError 消息无效,在任何发送之前。field 指明字段,status 为 400。 是
MailConnectionError DNS、连接被拒绝或重置、TLS 或证书。cause 持有 socket 错误。 否,但配置问题除外,例如要求 STARTTLS 时服务器不支持
MailTimeoutError 某阶段超过超时。带 phase 与 timeoutMs。 否
MailSmtpError SMTP 错误回复。带 code、enhancedCode、command 和 response。 5xx 回复为是
MailRecipientsRejectedError 服务器拒绝一个或多个收件人,且未发送任何内容。rejected 列出它们。继承 MailSmtpError。 任一拒绝为 5xx 时是
MailTemplateError 模板缺失或无法编译,或邮件指定了模板但没有模板引擎。带 template,文件内问题还带 file、line 和 column。 是
MailProviderError HTTP 提供方拒绝了请求。带 code(HTTP 状态)、provider、providerCode,响应有有效 Retry-After 时带 retryAfterMs。 除 408、409、429 之外的 4xx 为是