const nodemailer = require('nodemailer'); const schedule = require('node-schedule'); const db2 = require('../config/db2'); // connect to zenclouddb for mail 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 db2.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 // Modify By Michael 20260310 text: row.content }); 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 db2.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();