6

Express实现定时发送邮件 - 书中枫叶

 1 year ago
source link: https://www.cnblogs.com/zy-mg/p/17303574.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Express实现定时发送邮件

Posted on 2023-04-10 17:10  书中枫叶  阅读(78)  评论(0)  编辑  收藏  举报

在开发中我们有时候需要每隔 一段时间发送一次电子邮件,或者在某个特定的时间进行发送邮件
无需手动去操作,基于这样的情况下我们需要用到了定时任务,一般可以写个定时器,来完成相应的需求,在 node.js 中自已实现也非常容易,接下来要介绍的是node-schedule来完成定时任务

用express.js实现 每个星期三中午12点 发送邮件给某个用户

1.安装第三方库 Node Schedule、nodemailer

npm i -s node-schedule nodemailer

2.新建一个 TaskScheduler 定时任务类

// 引入 node-schedule 模块const schedule = require('node-schedule'); /** TODO:编写 Cron 表达式时,有五个占位符可以使用,分别表示分钟、小时、日期、月份和星期几。* 每个占位符可以使用特定的值、值范围、逗号分隔的值列表和通配符等等** * * * * * ** | | | | | |* | | | | | day of week* | | | | month* | | | day of month* | | hour* | minute* second ( optional )** 示例 Cron 表达式:* 每分钟的第30秒触发: 30 * * * * ** 每小时的1分30秒触发 :30 1 * * * ** 每天的凌晨1点1分30秒触发 :30 1 1 * * ** 每月的1日1点1分30秒触发 :30 1 1 1 * ** 每年的1月1日1点1分30秒触发 :30 1 1 1 1 ** 每周1的1点1分30秒触发 :30 1 1 * * 1* */ // 创建一个任务调度器类class TaskScheduler { // 构造函数,接受 cron 表达式和要执行的任务作为参数 constructor(cronExpression, task) { // 将传入的 cron 表达式和任务保存为成员变量 this.cronExpression = cronExpression; this.task = task; // 初始化 job 为 null this.job = null; } // 启动任务 start() { // 如果当前没有正在运行的任务,则创建新的任务 if (!this.job) { this.job = schedule.scheduleJob(this.cronExpression, this.task); console.log(`定时任务启动: ${this.cronExpression}`); } } // 停止任务 stop() { // 如果当前有正在运行的任务,则取消任务并将 job 设为 null if (this.job) { this.job.cancel(); console.log(`定时任务停止: ${this.cronExpression}`); this.job = null; } }} // 导出任务调度器类module.exports = TaskScheduler;

3.创建一个发送邮件的方法

const nodemailer = require("nodemailer");/** * 邮箱发送 * * @param {string} to 对方邮箱 * @param {string} content 发送内容 */ // 创建Nodemailer传输器 SMTP 或者 其他 运输机制let transporter = nodemailer.createTransport( { service: 'QQ', // 使用内置传输发送邮件 查看支持列表:https://nodemailer.com/smtp/well-known/ port: 465, // SMTP 端口 secureConnection: true, // 使用 SSL auth: { user: '[email protected]', // 发送方邮箱的账号 pass: '******', // 邮箱授权密码 } }); exports.send = (to, content) => { return new Promise((resolve, reject) => { transporter.sendMail({ from: `"ZY.API" <[email protected]>`, // 发送方邮箱的账号 to: to, // 邮箱接受者的账号 subject: "Welcome to ZY.API", // Subject line // text: '"MG'Blog ?"', // 文本内容 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 href="http://www.zhouyi.run/#/">ZY.API</a></p> <p style="font-weight: bold">${content}</p> <p ><a style="font-size: 18px;font-weight: bolder" href="http://www.zhouyi.run/#/">确认</a></p> <p style="text-indent: 2em;">祝您工作顺利,心想事成</p>` }, (error, info) => { if (error) { reject(error) } resolve(info) }); })}

4.创建一个 每个星期三中午12点 发送邮件的任务实例并且引入发送邮件的方法

const TaskScheduler = require('./TaskScheduler')const {send} = require('../../utils/utils.mailer') const task = async function () { await send('[email protected]', '每个星期三中午12点 发送邮件') return console.log('允许定时任务每个星期三中午12点 发送邮件...' + new Date().getMinutes() + "-" + new Date().getSeconds());}; // 创建一个 每个星期三中午12点 发送邮件module.exports = new TaskScheduler('0 0 12 ? * WED', task);

5.路由使用该定时发送邮件类

/** *@author ZY *@date 2023/4/10 *@Description:任务相关的接口 */ const express = require('express');const router = express.Router();const SendEmail = require('../../scheduler/task/SendEmail') /****************************************************************************/ /** * 开始发送邮件定时任务 * @route GET /v1/task/startSendEmail * @group 定时任务 - 定时任务相关 * @returns {object} 200 - {"status": 1,"message": "登录成功.","data": {...},"time": 1680598858753} * @returns {Error} default - Unexpected error */ router.get('/startSendEmail', function (req, res) { //用户的定时任务开始 SendEmail.start(); res.send('用户的定时任务开始!');}); /** * 停止发送邮件定时任务 * @route GET /v1/task/stopSendEmail * @group 定时任务 - 定时任务相关 * @returns {object} 200 - {"status": 1,"message": "登录成功.","data": {...},"time": 1680598858753} * @returns {Error} default - Unexpected error */ router.get('/stopSendEmail', function (req, res) { SendEmail.stop(); res.send('用户的定时任务开始!');}); module.exports = router;

6.到这里差不多就可以开始定时任务和停止定时任务了,我这里是设置30秒发一次邮件

image.png
e747763d0a54354115cc9b00fda0f34.jpg

狂点这里查看完整项目代码


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK