First Commit

This commit is contained in:
DATAEXPRESS\4734
2026-01-06 18:24:42 +08:00
commit 65f033adbc
37 changed files with 3010 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
const nodemailer = require('nodemailer');
const schedule = require('node-schedule');
const db = require('../config/db');
const logger = require('../utils/logger'); // 必須引入!
class MailService {
constructor() {
this.transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: { user: process.env.MAIL_USER, pass: process.env.MAIL_PASS }
});
}
async initAutoMail() {
// 每 30 秒執行一次
schedule.scheduleJob('*/30 * * * * *', async () => {
try {
// 增加一個簡單的連線檢查,避免資料庫掛掉時噴錯
const [rows] = await db.query('SELECT * FROM zen_mail_list WHERE mail_status = 0 LIMIT 10');
if (rows.length > 0) {
logger.info(`AutoMail: Processing ${rows.length} messages.`);
}
for (let row of rows) {
try {
await this.transporter.sendMail({
from: process.env.MAIL_USER,
to: row.recipient,
subject: row.mail_subject,
html: row.content
});
await db.query('UPDATE zen_mail_list SET mail_status = 1, sent_at = NOW() WHERE id = ?', [row.id]);
} catch (mailErr) {
logger.error(`Mail ID ${row.id} failed: ${mailErr.message}`);
await db.query('UPDATE zen_mail_list SET mail_status = 9, error_log = ? WHERE id = ?', [mailErr.message, row.id]);
}
}
} catch (dbErr) {
// 這裡現在可以正確使用 logger 了
logger.error(`AutoMail Job DB Failure: ${dbErr.message}`);
}
});
}
}
module.exports = new MailService();