fix mail function

This commit is contained in:
DATAEXPRESS\4734
2026-03-10 18:06:15 +08:00
parent c04314a7b0
commit 86e07c98e1
3 changed files with 37 additions and 5 deletions
+29
View File
@@ -0,0 +1,29 @@
const mysql = require('mysql2/promise');
require('dotenv').config();
const pool2 = mysql.createPool({
host: process.env.DB_HOST,
port: process.env.DB_PORT || 3306,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.MAIL_DB_NAME,
waitForConnections: true,
connectionLimit: 15, // 增加併發處理能力
queueLimit: 0,
multipleStatements: true,
charset: 'utf8mb4', // 確保這一行存在
timezone: '+08:00', // 強制時區一致
dateStrings: true // 強制將日期作為字串回傳,避免 Node.js 進行二次時區轉換
});
// 啟動測試
pool2.getConnection()
.then(conn => {
console.log('✅ MariaDB Connected Successfully.');
conn.release();
})
.catch(err => {
console.error('❌ MariaDB Connection Failed:', err.message);
});
module.exports = pool2;
+7 -5
View File
@@ -1,6 +1,6 @@
const nodemailer = require('nodemailer');
const schedule = require('node-schedule');
const db = require('../config/db');
const db2 = require('../config/db2'); // connect to zenclouddb for mail
const logger = require('../utils/logger'); // 必須引入!
class MailService {
@@ -18,7 +18,7 @@ class MailService {
schedule.scheduleJob('*/30 * * * * *', async () => {
try {
// 增加一個簡單的連線檢查,避免資料庫掛掉時噴錯
const [rows] = await db.query('SELECT * FROM zen_mail_list WHERE mail_status = 0 LIMIT 10');
const [rows] = await db2.query('SELECT * FROM zen_mail_list WHERE mail_status = 0 LIMIT 10');
if (rows.length > 0) {
logger.info(`AutoMail: Processing ${rows.length} messages.`);
@@ -30,12 +30,14 @@ class MailService {
from: process.env.MAIL_USER,
to: row.recipient,
subject: row.mail_subject,
html: row.content
// html: row.content
// Modify By Michael 20260310
text: row.content
});
await db.query('UPDATE zen_mail_list SET mail_status = 1, sent_at = NOW() WHERE id = ?', [row.id]);
await db2.query('UPDATE zen_mail_list SET mail_status = 1, create_date = 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]);
await db2.query('UPDATE zen_mail_list SET mail_status = 9, error_log = ? WHERE id = ?', [mailErr.message, row.id]);
}
}
} catch (dbErr) {