node.js 邮箱定时任务

110 阅读1分钟

package.json

{
  "name": "2",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "axios": "^1.5.0",
    "node-schedule": "^2.1.1",
    "nodemailer": "^6.9.5"
  }
}

主要代码:

const axios = require("axios");
// 邮箱发送模块
const nodemailer = require("nodemailer");
// 定时任务模块
const schedule = require('node-schedule');

// 发送HTTP GET请求
//我这边使用的是高德的api
async function sendMail() {
  let res = await axios.get(
    "https://restapi.amap.com/v3/weather/weatherInfo?parameters=&key=这里填入你自己申请的key&city=320506"
  );
  let weatherInfo = res.data.lives[0];

  const regex = /雨/;
  const isMatched = regex.test(weatherInfo.weather) ? "需要带伞" : "无需带伞";

  let text = `今日${weatherInfo.province}省苏州市${weatherInfo.city}天气情况:
    天气:${weatherInfo.weather},
    实时气温:${weatherInfo.temperature},
    风向:${weatherInfo.winddirection},
    风力:${weatherInfo.windpower},
    空气湿度:${weatherInfo.humidity},
    更新时间:${weatherInfo.reporttime},
    判断:${isMatched}
    `;
  
  //发送人
  var user = "xxxx@qq.com"; //自己的邮箱
  var pass = "填入你自己的邮箱授权码"; //邮箱授权码获取方法自行百度
  var to = "xxxx@qq.com"; //对方的邮箱
  let transporter = nodemailer.createTransport({
    host: "smtp.qq.com",
    port: 587,
    secure: false,
    auth: {
      user, // 用户账号
      pass, //授权码,通过QQ获取
    },
  });
  let info = await transporter.sendMail({
    from: `我的天气助手<${user}>`, // sender address
    to: `本邮箱<${to}>`, // list of receivers
    subject: "每日天气", // Subject line
    text, // plain text body
  });
  console.log("发送成功");
}



// 创建一个每天的定时任务,在每天的8点执行
// 前三个参数为 秒 分 时
const job = schedule.scheduleJob("0 10 8 * * *", sendMail);
const job2 = schedule.scheduleJob("0 10 13 * * *", sendMail);