Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 22: Gửi mail trong Express

Tiếp tục với series, bài này mình sẽ giới thiệu với mọi người về gửi mail trong Express: người đọc bình luận bài viết, MiniBlog gửi mail báo cho tác giả.

1. Gửi mail với Nodemailer.

Ứng dụng gửi mail qua một máy chủ SMTP (Gmail, SendGrid, Amazon SES...). Mình dùng package nodemailer (bản 10.5.0), cả ứng dụng dùng chung một transporter (đối tượng giữ cấu hình SMTP):

- lib/mailer.js

import nodemailer from 'nodemailer';

// Máy chủ SMTP: ở local là Mailpit, production là dịch vụ gửi mail thật
const transporter = nodemailer.createTransport(
    {
        host: process.env.SMTP_HOST,
        port: Number(process.env.SMTP_PORT),
        // SMTP_USER để trống (Mailpit) thì gửi không cần đăng nhập
        auth: process.env.SMTP_USER
            ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
            : undefined,
        connectionTimeout: 10 * 1000, // tối đa 10 giây (mặc định 2 phút)
    },
    { from: process.env.MAIL_FROM }, // mặc định cho mọi mail
);

export default transporter;

Trong đó:

  • Tham số đầu là cấu hình SMTP lấy từ biến môi trường (mật khẩu không nằm trong code), tham số thứ hai là giá trị mặc định cho mọi mail.
  • Không cần option secure: cổng 465 tự dùng TLS, cổng khác tự nâng lên TLS (STARTTLS) nếu máy chủ hỗ trợ.

2. Test mail bằng Mailpit.

Khi phát triển đừng gửi mail thật. Mailpit là máy chủ SMTP giả: nhận mọi mail ở cổng 1025, không gửi đi đâu, chỉ hiện lên giao diện web ở cổng 8025. Các bạn cài nodemailer và chạy Mailpit bằng Docker như MySQL ở Bài 12:

npm install nodemailer
docker run -d --name miniblog-mailpit -p 127.0.0.1:1025:1025 -p 127.0.0.1:8025:8025 axllent/mailpit:v1.33.1

Thêm vào cuối .env và .env.example:

# Địa chỉ của trang, dùng để tạo link trong mail
APP_URL=http://localhost:3000

# Máy chủ gửi mail, ở local là Mailpit (cổng chỉ mở trên 127.0.0.1)
SMTP_HOST=127.0.0.1
SMTP_PORT=1025
SMTP_USER=
SMTP_PASS=
MAIL_FROM="MiniBlog <[email protected]>"

Link trong mail phải là URL đầy đủ nên cần APP_URL. Mailpit mặc định không yêu cầu đăng nhập nên SMTP_USER để trống; lên production thì điền thông tin của dịch vụ gửi mail.

3. Template mail.

Mail HTML cũng là một view EJS (Bài 8):

- views/emails/new-comment.ejs

<p>Chào <%= author.name %>,</p>
<p><strong><%= comment.name %></strong> vừa bình luận bài viết <a href="<%= url %>"><%= post.title %></a>:</p>
<blockquote style="white-space: pre-line"><%= comment.content %></blockquote>
<p>MiniBlog</p>

Tên và nội dung bình luận do người lạ gõ nên phải in bằng <%= %> để được escape, dùng <%- %> là ai cũng chèn được link lừa đảo vào mail gửi tác giả.

- services/mail-service.js

import ejs from 'ejs';
import transporter from '../lib/mailer.js';

const EMAIL_VIEWS = import.meta.dirname + '/../views/emails';

// Báo cho tác giả có bình luận mới, gửi cả bản HTML và bản chữ thường
export async function sendNewCommentMail({ author, post, comment }) {
    const url = `${process.env.APP_URL}/posts/${post.slug}`;
    const html = await ejs.renderFile(`${EMAIL_VIEWS}/new-comment.ejs`, { author, post, comment, url });
    await transporter.sendMail({
        to: { name: author.name, address: author.email },
        subject: `Bình luận mới: ${post.title}`,
        text: `Chào ${author.name},\n\n${comment.name} vừa bình luận bài viết "${post.title}":\n\n${comment.content}\n\nXem bài viết: ${url}`,
        html,
    });
}

ejs.renderFile() không truyền callback thì trả về Promise. Ngoài html, mail có thêm text (chữ thường, không escape) cho trình đọc mail không hiện HTML.

4. Thêm bình luận cho bài viết.

Bảng comments (post_id, name, content) đã có từ Bài 12, giờ mình làm form bình luận, ai cũng gửi được:

- models/comment.js

import pool from '../lib/db.js';

export async function findByPost(postId) {
    const [rows] = await pool.execute(
        'SELECT name, content FROM comments WHERE post_id = ? ORDER BY id',
        [postId],
    );
    return rows;
}

export async function create({ postId, name, content }) {
    await pool.execute(
        'INSERT INTO comments (post_id, name, content) VALUES (?, ?, ?)',
        [postId, name, content],
    );
}

- validators/comment.js

import { body } from 'express-validator';

export const commentRules = [
    body('name')
        .isString().withMessage('Tên không hợp lệ')
        .bail()
        .trim()
        .isLength({ min: 2, max: 100 }).withMessage('Tên phải từ 2 đến 100 ký tự'),
    body('content')
        .isString().withMessage('Bình luận không hợp lệ')
        .bail()
        .trim()
        .isLength({ min: 2, max: 2000 }).withMessage('Bình luận phải từ 2 đến 2000 ký tự'),
];

- controllers/post-controller.js (đoạn thay đổi)

import * as commentService from '../services/comment-service.js';

export async function show(req, res) {
    const post = await postService.getPostBySlug(req.params.slug);
    const comments = await commentService.listComments(post.id);
    res.render('posts/show', { title: post.title, post, comments });
}

// POST /posts/:id/comments: ai cũng bình luận được, không cần đăng nhập
export async function storeComment(req, res) {
    const post = await postService.getPostById(req.params.id);
    const result = validationResult(req);
    if (result.isEmpty()) {
        await commentService.addComment(post, matchedData(req));
        req.session.flash = { type: 'success', message: 'Đã gửi bình luận' };
    } else {
        req.session.flash = { type: 'error', message: result.array()[0].msg };
    }
    res.redirect(303, `/posts/${post.slug}`);
}

Dữ liệu sai thì báo lỗi đầu tiên bằng flash message. Mỗi bình luận là một mail nên route có thêm commentLimiter như Bài 17:

- routes/posts.js (đoạn thay đổi)

import { commentRules } from '../validators/comment.js';
import { commentLimiter } from '../middlewares/rate-limit.js';

// ... các route cũ giữ nguyên ...
router.post('/:id/comments', commentLimiter, commentRules, postController.storeComment);

- middlewares/rate-limit.js (thêm vào cuối file)

// Mỗi IP gửi tối đa 5 bình luận trong 15 phút
export const commentLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    limit: 5,
    standardHeaders: 'draft-8',
    legacyHeaders: false,
    handler: (req, res, next, options) => {
        next(new HttpError(options.statusCode, 'Bạn gửi quá nhiều bình luận, vui lòng thử lại sau 15 phút'));
    },
});

- views/posts/show.ejs (thêm ngay trước dòng include footer)

<section id="comments">
    <h2>Bình luận (<%= comments.length %>)</h2>
    <% comments.forEach((comment) => { %>
    <p><strong><%= comment.name %></strong>:</p>
    <p class="post-content"><%= comment.content %></p>
    <% }) %>
    <form method="post" action="/posts/<%= post.id %>/comments">
        <input type="hidden" name="_csrf" value="<%= csrfToken() %>">
        <p><input name="name" placeholder="Tên của bạn" required maxlength="100"></p>
        <p><textarea name="content" rows="4" placeholder="Bình luận" required maxlength="2000"></textarea></p>
        <button type="submit">Gửi bình luận</button>
    </form>
</section>

Form cần csrfToken() nên từ giờ ai mở trang bài viết, kể cả bot, cũng được tạo một session (cookie và một dòng trong bảng sessions): cái giá của bảo vệ CSRF cho form công khai. Session hết hạn sau 1 ngày, express-mysql-session tự dọn 15 phút một lần.

5. Gửi mail không chặn request.

Máy chủ SMTP treo thì riêng bước kết nối mất 10 giây (connectionTimeout). Nếu await việc gửi, người bình luận phải chờ theo, mail lỗi thì bình luận đã lưu mà vẫn hiện trang lỗi. Vì vậy service lưu bình luận xong là trả về, mail gửi sau:

- services/comment-service.js

import * as Comment from '../models/comment.js';
import { getUser } from './auth-service.js';
import { sendNewCommentMail } from './mail-service.js';

export function listComments(postId) {
    return Comment.findByPost(postId);
}

// Lưu bình luận rồi gửi mail cho tác giả, không chờ mail gửi xong
export async function addComment(post, { name, content }) {
    await Comment.create({ postId: post.id, name, content });
    notifyAuthor(post, { name, content }).catch((err) => {
        console.error('Không gửi được mail bình luận mới:', err);
    });
}

// Bài viết có tác giả thì gửi mail cho tác giả
async function notifyAuthor(post, comment) {
    const author = post.author_id ? await getUser(post.author_id) : null;
    if (author) {
        await sendNewCommentMail({ author, post, comment });
    }
}

notifyAuthor() không có await nhưng bắt buộc có .catch(): từ Node.js 15, Promise bị reject mà không ai bắt sẽ làm dừng cả server. Bài không có tác giả (như 2 bài của npm run db:seed) thì không gửi mail.

Để thử, các bạn chạy npm run dev, đăng nhập, viết một bài mới rồi bình luận vào bài đó. Mở http://localhost:8025 sẽ thấy mail "Bình luận mới: ..." gửi tới email của bạn, bình luận có <b> thì mail hiện nguyên chữ <b>. Tắt Mailpit (docker stop miniblog-mailpit) rồi bình luận lại: trang vẫn báo "Đã gửi bình luận", terminal ghi:

# Không gửi được mail bình luận mới: Error: connect ECONNREFUSED 127.0.0.1:1025
# ... (stack trace)

Thử xong thì docker start miniblog-mailpit và chạy npm run db:seed để xoá bài, bình luận thử. Cách gửi này đủ cho MiniBlog, nhưng server tắt đúng lúc đang gửi thì mất mail; ứng dụng lớn thường dùng hàng đợi (queue, VD: BullMQ) để gửi lại khi lỗi.

Code đầy đủ của MiniBlog sau bài này nằm ở tag bai-22 trên GitHub; các thay đổi của riêng bài này: so sánh bai-21...bai-22.

6. Lời kết.

Như vậy là chúng ta đã xong gửi mail trong Express: Nodemailer, Mailpit để test, template mail bằng EJS và gửi mail không chặn request. Lỗi gửi mail mới chỉ ghi bằng console.error, bài sau mình sẽ giới thiệu với mọi người về logging và cấu hình trong Express.

Đă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!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha