NestJS Mailer 模块使用教程
1. 项目介绍
NestJS Mailer 是一个用于 NestJS 框架的邮件发送模块。它基于 Nodemailer,提供了简单易用的接口来发送电子邮件。该模块支持多种邮件传输方式,包括 SMTP、SendGrid、Mailgun 等,并且可以轻松集成到 NestJS 应用中。
2. 项目快速启动
2.1 安装依赖
首先,你需要在你的 NestJS 项目中安装 @nestjs-modules/mailer 和 @nestjs/config 包:
npm install @nestjs-modules/mailer nodemailer
npm install @nestjs/config
2.2 配置邮件服务
在 src/app.module.ts 文件中配置邮件服务:
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot(),
MailerModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (config: ConfigService) => ({
transport: {
host: config.get('MAIL_HOST'),
port: config.get('MAIL_PORT'),
secure: false,
auth: {
user: config.get('MAIL_USER'),
pass: config.get('MAIL_PASSWORD'),
},
},
defaults: {
from: `"No Reply" <${config.get('MAIL_FROM')}>`,
},
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}
2.3 发送邮件
创建一个邮件服务类 src/mail/mail.service.ts:
import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';
@Injectable()
export class MailService {
constructor(private mailerService: MailerService) {}
async sendWelcomeEmail(to: string) {
await this.mailerService.sendMail({
to,
subject: 'Welcome to our service!',
template: 'welcome', // 使用模板引擎
context: {
name: 'John Doe',
},
});
}
}
2.4 配置模板引擎
在 src/mail/templates 目录下创建一个 welcome.hbs 模板文件:
<h1>Welcome, {{name}}!</h1>
<p>Thank you for joining our service.</p>
2.5 使用邮件服务
在控制器或服务中使用邮件服务:
import { Controller, Post, Body } from '@nestjs/common';
import { MailService } from './mail/mail.service';
@Controller('mail')
export class MailController {
constructor(private mailService: MailService) {}
@Post('send')
async sendEmail(@Body('email') email: string) {
await this.mailService.sendWelcomeEmail(email);
return { message: 'Email sent' };
}
}
3. 应用案例和最佳实践
3.1 用户注册欢迎邮件
在用户注册成功后,发送一封欢迎邮件。可以使用模板引擎来动态生成邮件内容,例如用户的名字。
3.2 密码重置邮件
当用户请求重置密码时,发送一封包含重置链接的邮件。确保链接的安全性,并在邮件中包含过期时间。
3.3 订单确认邮件
在用户下单后,发送一封订单确认邮件,包含订单详情和预计送达时间。
4. 典型生态项目
4.1 NestJS
NestJS 是一个用于构建高效、可扩展的 Node.js 服务器端应用程序的框架。NestJS Mailer 模块是 NestJS 生态系统的一部分,提供了强大的邮件发送功能。
4.2 Nodemailer
Nodemailer 是一个用于发送电子邮件的 Node.js 模块。NestJS Mailer 模块基于 Nodemailer,提供了更高层次的抽象,方便在 NestJS 应用中使用。
4.3 Handlebars
Handlebars 是一个简单的模板引擎,可以用于生成动态的 HTML 内容。NestJS Mailer 支持使用 Handlebars 模板引擎来生成邮件内容。
通过以上步骤,你可以快速上手并使用 NestJS Mailer 模块来发送电子邮件。希望这篇教程对你有所帮助!
GLM-5智谱 AI 正式发布 GLM-5,旨在应对复杂系统工程和长时域智能体任务。Jinja00
GLM-5-w4a8GLM-5-w4a8基于混合专家架构,专为复杂系统工程与长周期智能体任务设计。支持单/多节点部署,适配Atlas 800T A3,采用w4a8量化技术,结合vLLM推理优化,高效平衡性能与精度,助力智能应用开发Jinja00- QQwen3.5-397B-A17BQwen3.5 实现了重大飞跃,整合了多模态学习、架构效率、强化学习规模以及全球可访问性等方面的突破性进展,旨在为开发者和企业赋予前所未有的能力与效率。Jinja00
three-cesium-examplesthree.js cesium.js 原生案例JavaScript00
weapp-tailwindcssweapp-tailwindcss - bring tailwindcss to weapp ! 把 tailwindcss 原子化思想带入小程序开发吧 !TypeScript00
CherryUSBCherryUSB 是一个小而美的、可移植性高的、用于嵌入式系统(带 USB IP)的高性能 USB 主从协议栈C00