Express實現(xiàn)定時發(fā)送郵件的示例代碼
在開發(fā)中我們有時候需要每隔 一段時間發(fā)送一次電子郵件,或者在某個特定的時間進行發(fā)送郵件,無需手動去操作,基于這樣的情況下我們需要用到了定時任務(wù),一般可以寫個定時器,來完成相應(yīng)的需求,在 node.js 中自已實現(xiàn)也非常容易,接下來要介紹的是node-schedule來完成定時任務(wù)
用express.js實現(xiàn) 每個星期三中午12點 發(fā)送郵件給某個用戶
1.安裝第三方庫 Node Schedule、nodemailer
npm i -s node-schedule nodemailer
2.新建一個 TaskScheduler 定時任務(wù)類
// 引入 node-schedule 模塊 const schedule = require('node-schedule'); /* * TODO:編寫 Cron 表達式時,有五個占位符可以使用,分別表示分鐘、小時、日期、月份和星期幾。 * 每個占位符可以使用特定的值、值范圍、逗號分隔的值列表和通配符等等 * * * * * * * * * | | | | | | * | | | | | day of week * | | | | month * | | | day of month * | | hour * | minute * second ( optional ) * * 示例 Cron 表達式: * 每分鐘的第30秒觸發(fā): 30 * * * * * * 每小時的1分30秒觸發(fā) :30 1 * * * * * 每天的凌晨1點1分30秒觸發(fā) :30 1 1 * * * * 每月的1日1點1分30秒觸發(fā) :30 1 1 1 * * * 每年的1月1日1點1分30秒觸發(fā) :30 1 1 1 1 * * 每周1的1點1分30秒觸發(fā) :30 1 1 * * 1 * */ // 創(chuàng)建一個任務(wù)調(diào)度器類 class TaskScheduler { // 構(gòu)造函數(shù),接受 cron 表達式和要執(zhí)行的任務(wù)作為參數(shù) constructor(cronExpression, task) { // 將傳入的 cron 表達式和任務(wù)保存為成員變量 this.cronExpression = cronExpression; this.task = task; // 初始化 job 為 null this.job = null; } // 啟動任務(wù) start() { // 如果當前沒有正在運行的任務(wù),則創(chuàng)建新的任務(wù) if (!this.job) { this.job = schedule.scheduleJob(this.cronExpression, this.task); console.log(`定時任務(wù)啟動: ${this.cronExpression}`); } } // 停止任務(wù) stop() { // 如果當前有正在運行的任務(wù),則取消任務(wù)并將 job 設(shè)為 null if (this.job) { this.job.cancel(); console.log(`定時任務(wù)停止: ${this.cronExpression}`); this.job = null; } } } // 導出任務(wù)調(diào)度器類 module.exports = TaskScheduler;
3.創(chuàng)建一個發(fā)送郵件的方法
const nodemailer = require("nodemailer"); /** * 郵箱發(fā)送 * * @param {string} to 對方郵箱 * @param {string} content 發(fā)送內(nèi)容 */ // 創(chuàng)建Nodemailer傳輸器 SMTP 或者 其他 運輸機制 let transporter = nodemailer.createTransport( { service: 'QQ', // 使用內(nèi)置傳輸發(fā)送郵件 查看支持列表:https://nodemailer.com/smtp/well-known/ port: 465, // SMTP 端口 secureConnection: true, // 使用 SSL auth: { user: '1840354092@qq.com', // 發(fā)送方郵箱的賬號 pass: '******', // 郵箱授權(quán)密碼 } } ); exports.send = (to, content) => { return new Promise((resolve, reject) => { transporter.sendMail({ from: `"ZY.API" <1840354092@qq.com>`, // 發(fā)送方郵箱的賬號 to: to, // 郵箱接受者的賬號 subject: "Welcome to ZY.API", // Subject line // text: '"MG'Blog ?"', // 文本內(nèi)容 html: ` <img src="http://www.zhouyi.run:3001/api/v1/files/preview?p=pexels-photo-276452.jpeg&&mimetype=image/jpeg" alt="" style="height:auto;display:block;" /> <p >??? <a >ZY.API</a></p> <p style="font-weight: bold">${content}</p> <p ><a style="font-size: 18px;font-weight: bolder" >確認</a></p> <p style="text-indent: 2em;">祝您工作順利,心想事成</p>` }, (error, info) => { if (error) { reject(error) } resolve(info) }); }) }
4.創(chuàng)建一個 每個星期三中午12點 發(fā)送郵件的任務(wù)實例并且引入發(fā)送郵件的方法
const TaskScheduler = require('./TaskScheduler') const {send} = require('../../utils/utils.mailer') const task = async function () { await send('1840354092@qq.com', '每個星期三中午12點 發(fā)送郵件') return console.log('允許定時任務(wù)每個星期三中午12點 發(fā)送郵件...' + new Date().getMinutes() + "-" + new Date().getSeconds()); }; // 創(chuàng)建一個 每個星期三中午12點 發(fā)送郵件 module.exports = new TaskScheduler('0 0 12 ? * WED', task);
5.路由使用該定時發(fā)送郵件類
/** *@author ZY *@date 2023/4/10 *@Description:任務(wù)相關(guān)的接口 */ const express = require('express'); const router = express.Router(); const SendEmail = require('../../scheduler/task/SendEmail') /****************************************************************************/ /** * 開始發(fā)送郵件定時任務(wù) * @route GET /v1/task/startSendEmail * @group 定時任務(wù) - 定時任務(wù)相關(guān) * @returns {object} 200 - {"status": 1,"message": "登錄成功.","data": {...},"time": 1680598858753} * @returns {Error} default - Unexpected error */ router.get('/startSendEmail', function (req, res) { //用戶的定時任務(wù)開始 SendEmail.start(); res.send('用戶的定時任務(wù)開始!'); }); /** * 停止發(fā)送郵件定時任務(wù) * @route GET /v1/task/stopSendEmail * @group 定時任務(wù) - 定時任務(wù)相關(guān) * @returns {object} 200 - {"status": 1,"message": "登錄成功.","data": {...},"time": 1680598858753} * @returns {Error} default - Unexpected error */ router.get('/stopSendEmail', function (req, res) { SendEmail.stop(); res.send('用戶的定時任務(wù)開始!'); }); module.exports = router;
6.到這里差不多就可以開始定時任務(wù)和停止定時任務(wù)了,我這里是設(shè)置30秒發(fā)一次郵件
到此這篇關(guān)于Express實現(xiàn)定時發(fā)送郵件的示例代碼的文章就介紹到這了,更多相關(guān)Express定時發(fā)送郵件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Puppeteer 爬取動態(tài)生成的網(wǎng)頁實戰(zhàn)
這篇文章主要介紹了Puppeteer 爬取動態(tài)生成的網(wǎng)頁實戰(zhàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11NPM相關(guān)命令之報錯node-gyp...的解決方法
node-gyp就是為node編譯c++擴展的時候使用的編譯工具,下面這篇文章主要給大家介紹了關(guān)于NPM相關(guān)命令之報錯node-gyp...的解決方法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-09-09