Tiếp tục với series, TaskFlow cần báo cho người dùng khi có việc: mail chào mừng sau khi đăng ký, mail báo khi được giao task. Bài này mình sẽ giới thiệu với mọi người về gửi mail trong NestJS.
1. Gửi mail trong NestJS và Mailpit.
Thay vì nodemailer, mình dùng package chính thức @nestjs/mail (tài liệu): tự gửi SMTP, template tự escape, tự thử lại khi lỗi tạm thời, không có dependency. Nó mới ở bản 0.0.2 nên API có thể đổi.
Ở local đừng gửi mail thật. Mailpit là SMTP server giả: nhận mail ở cổng 1025, hiển thị ở web cổng 8025:
docker run -d --name taskflow-mailpit -p 127.0.0.1:1025:1025 -p 127.0.0.1:8025:8025 axllent/mailpit:v1.33.1
npm install @nestjs/mail
2. Cấu hình SMTP qua ConfigService.
Như REDIS_URL ở Bài 27: thêm SMTP_URL="smtp://localhost:1025" và MAIL_FROM="TaskFlow <[email protected]>" vào .env, .env.example; thêm SMTP_URL: z.url({ protocol: /^smtps?$/ }) và MAIL_FROM (có mặc định) vào envSchema; tạo src/config/mail.config.ts là registerAs('mail', ...) trả về smtpUrl, from rồi thêm vào load (Bài 14).
Phần mail gom vào module riêng: nest g module notifications --format, nest g service notifications --no-spec --format.
- src/notifications/notifications.module.ts
import { Module } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import { FileTemplateEngine, MailModule, SmtpTransport } from '@nestjs/mail';
import { join } from 'node:path';
import mailConfig from '../config/mail.config.js';
import { NotificationsService } from './notifications.service.js';
import { TaskAssignedMail } from './task-assigned.mail.js';
import { WelcomeMail } from './welcome.mail.js';
@Module({
imports: [
// MailModule mặc định là global, cung cấp Mailer
MailModule.forRootAsync({
inject: [mailConfig.KEY],
useFactory: (mail: ConfigType<typeof mailConfig>) => ({
transport: new SmtpTransport({ url: mail.smtpUrl }),
templates: new FileTemplateEngine({
dir: join(import.meta.dirname, 'templates'),
layout: 'layout',
}),
from: mail.from,
}),
}),
],
providers: [NotificationsService, WelcomeMail, TaskAssignedMail],
exports: [NotificationsService],
})
export class NotificationsModule {}
Trong đó:
SmtpTransport: host kháclocalhostthì bắt buộc STARTTLS, mật khẩu (trongSMTP_URL) không bao giờ đi qua kết nối không mã hoá.FileTemplateEngineđọc các file.htmltrongtemplates, bọc mọi mail tronglayout.html. Để file HTML được copy sangdist, thêm vàocompilerOptionscủanest-cli.json:"assets": ["notifications/templates/**/*"], "watchAssets": true.
3. Template HTML và mail class.
- src/notifications/templates/layout.html và welcome.html
<!doctype html>
<html>
<body style="font-family: Arial, sans-serif">
{{{ body }}}
<p>TaskFlow API</p>
</body>
</html>
<p>Chào {{ name }},</p>
<p>Tài khoản TaskFlow của bạn đã được tạo.</p>
<p>Đăng nhập rồi tạo project đầu tiên nhé!</p>
Cú pháp là một phần của Handlebars: {{ name }} chèn giá trị đã escape nên dữ liệu người dùng không chèn được HTML; {{{ body }}} chèn nguyên văn, chỉ dùng cho layout. Template không có helper.
Mỗi loại mail là một mail class, render() trả về subject, tên template và dữ liệu:
- src/notifications/welcome.mail.ts
import { Injectable } from '@nestjs/common';
import type { Mailable } from '@nestjs/mail';
export interface Welcome {
name: string;
}
@Injectable()
export class WelcomeMail implements Mailable<Welcome> {
render({ name }: Welcome) {
return {
subject: 'Chào mừng bạn đến với TaskFlow',
// templates/welcome.html, bọc trong templates/layout.html
template: 'welcome',
// Các giá trị template được dùng
context: { name },
};
}
}
4. Gửi mail không làm chậm request.
Gửi SMTP mất vài trăm mili giây, server mail có thể sập, mà user đã lưu rồi thì không được trả 500. Nên mình gửi sau khi ghi database và không await, như ActivitiesService.log() ở Bài 19:
- src/notifications/notifications.service.ts (đoạn trích, sendTaskAssigned() viết tương tự)
@Injectable()
export class NotificationsService {
private readonly logger = new Logger(NotificationsService.name);
constructor(private readonly mailer: Mailer) {}
sendWelcome(user: Recipient): void {
const sending = this.mailer.send(WelcomeMail, {
// Object { name, address }: tên có dấu phẩy vẫn là một người nhận
to: { name: user.name, address: user.email },
data: { name: user.name },
});
this.inBackground('WelcomeMail', sending);
}
// Không await: SMTP chậm hay lỗi cũng không làm chậm, không làm hỏng request
private inBackground(mail: string, sending: Promise<unknown>): void {
sending.catch((error: unknown) => {
// Mailer đã tự thử lại (mặc định 3 lần), vẫn lỗi thì ghi log
this.logger.error(`Không gửi được ${mail}`, error);
});
}
}
AuthModule import NotificationsModule, AuthService.register() gọi this.notifications.sendWelcome(user) ngay sau prisma.user.create(). Đăng ký gửi mail tới địa chỉ bất kỳ, nên register cũng có @Throttle 5 lần/phút như login (Bài 20).
Reset dữ liệu như Bài 27 rồi đăng ký An, mở http://localhost:8025 sẽ thấy mail. Mailpit cũng có API:
curl http://localhost:3000/api/v1/auth/register -H "Content-Type: application/json" \
-d '{"name":"Nguyen Van An","email":"[email protected]","password":"matkhau123"}'
# {"data":{"id":2,"name":"Nguyen Van An","email":"[email protected]","role":"user"}}
# Phần text (tự sinh từ HTML) của mail mới nhất
curl -s http://localhost:8025/api/v1/message/latest | node -pe 'JSON.parse(require("fs").readFileSync(0)).Text'
# Chào Nguyen Van An,
#
# Tài khoản TaskFlow của bạn đã được tạo.
# ...
Dừng Mailpit (docker stop taskflow-mailpit) rồi đăng ký Binh: vẫn 201 ngay, vài giây sau log có lỗi kèm đúng requestId của request (Bài 26):
{"level":"error",...,"requestId":"0614c6dc-a6bb-432d-b2f4-c5fe1afbff7a","context":"NotificationsService","error":{"name":"MailConnectionError","message":"SMTP connection to localhost:1025 failed: ECONNREFUSED",...},"message":"Không gửi được WelcomeMail"}
Lưu ý: Tắt ứng dụng thì MailModule chờ mail đang gửi xong (enableShutdownHooks()), nhưng process sập thì mail mất.
5. Mail khi giao task.
Cột assigneeId có sẵn nhưng chưa nhận từ request: thêm assigneeId?: number | null (@Field(() => Int, { nullable: true }), @IsOptional(), @IsInt()) vào CreateTaskDto và field vào TaskModel. Template task-assigned.html dùng {{ title }}, {{ projectName }}, {{#if dueDate}}...{{/if}}; TaskAssignedMail giống WelcomeMail, khác ở:
- src/notifications/task-assigned.mail.ts (đoạn trích trong render())
// Subject là header: gộp xuống dòng (title do user nhập) thành dấu cách
subject: `Bạn được giao task: ${title.replace(/\s+/g, ' ')}`,
// ...
dueDate: dueDate?.toLocaleDateString('vi-VN', {
timeZone: 'Asia/Ho_Chi_Minh',
}),
Subject có xuống dòng thì @nestjs/mail từ chối cả mail (chống header injection). TasksModule import NotificationsModule:
- src/tasks/tasks.service.ts (đoạn trích)
// Mail cho người được giao (assigneeId sai đã bị khoá ngoại chặn lại)
private async notifyAssignee(
assigneeId: number,
task: TaskWithRelations,
): Promise<void> {
const assignee = await this.prisma.user.findUniqueOrThrow({
where: { id: assigneeId },
select: { name: true, email: true },
});
this.notifications.sendTaskAssigned(assignee, {
title: task.title,
projectName: task.project.name,
dueDate: task.dueDate,
});
}
create() gọi nó sau lệnh ghi khi task.assigneeId !== null. update() lấy task cũ bằng findOne() và chỉ gửi khi assigneeId mới khác người cũ. assigneeId không tồn tại thì PrismaExceptionFilter trả 400, không có mail.
curl http://localhost:3000/api/v1/tasks -H "$A" -H "Content-Type: application/json" \
-d '{"projectId":1,"title":"Viết bài <Mail> & Mailpit","assigneeId":2,"dueDate":"2026-11-30T10:00:00.000Z"}'
# {"data":{"id":1,"title":"Viết bài <Mail> & Mailpit",...,"assigneeId":2,...}}
# HTML mail An nhận (phần trong layout):
# <p>Chào Nguyen Van An,</p>
# <p>Bạn vừa được giao task <strong>Viết bài <Mail> & Mailpit</strong>.</p>
# <p>Project: Website toidicode.com</p>
# <p>Hạn hoàn thành: 30/11/2026</p>
Chú ý: TaskFlow chưa có thành viên project nên giao được cho user bất kỳ. Tức là ai đăng nhập cũng khiến TaskFlow gửi mail với tiêu đề task, tên project tuỳ ý tới mọi user đã đăng ký, từ chính domain gửi mail của ứng dụng (tối đa 100 request/phút mỗi IP): một kênh spam, phishing làm hỏng uy tín domain. Thêm vào đó 400 và 201 cho biết user id nào tồn tại. Ứng dụng thật cần thành viên project (luồng mời vào project) và chỉ cho giao trong thành viên, kèm giới hạn số mail giao task theo từng user.
6. Lời kết.
Như vậy mình đã giới thiệu xong về gửi mail trong NestJS: cấu hình SMTP từ ConfigService, template HTML tự escape, mail class, gửi không chặn request và Mailpit. Để mail không mất khi process sập, bài sau mình sẽ giới thiệu về queue với BullMQ và chuyển mail giao task vào queue.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments