node.js 使用【七牛云SMS短信+邮件】给对象制作定时提醒

3,030 阅读2分钟

闲来无事,使用node.js七牛云SMS短信+邮件给女朋友做个每日提醒;

每天5点21发送短信

七牛云短信;需要申请签名、模板;效果如下图;

image.png

const qiniu = require('qiniu')
const axios = require('axios')
const schedule = require("node-schedule");

//每天5点21发送短信
  let rule = '21 17 * * *'
  let key = 'lovesms'
  if (schedule.scheduledJobs[key]) {
    schedule.scheduledJobs[key].cancel(); //先取消,然后重启
  }

  schedule.scheduleJob(key, rule, function () {
    sendsms()
  });

async function sendsms()  {
 const accessKey = 'accessKey'
    const secretKey = 'secretKey'
    const template_id = 'template_id'
    var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    let url = 'https://sms.qiniuapi.com/v1/message'
 var tel = new Array("110xxx");
    var reqBody = {
      template_id,
      "mobiles": tel,
      "parameters": {
        "code": "情话或祝福语;可以使用下面邮件的彩虹屁接口获取数据"
      }
    };
// 自己用axios写的方法
    reqBody = JSON.stringify(reqBody);
    let accessToken = generateAccessTokenV2(mac, url, 'POST', 'application/json', reqBody);

    let smsres = await axios.post(url, reqBody, {
      headers: { Authorization: accessToken, 'Content-Type': 'application/json' }
    })
    console.log(smsres.data);
 }
    
    
    // 生成token的方法
    // 创建 AccessToken 凭证
// @param mac            AK&SK对象
// @param requestURI     请求URL
// @param reqMethod      请求方法,例如 GET,POST
// @param reqContentType 请求类型,例如 application/json 或者  application/x-www-form-urlencoded
// @param reqBody        请求Body,仅当请求的 ContentType 为 application/json 或者
//                       application/x-www-form-urlencoded 时才需要传入该参数
exports.generateAccessTokenV2 = function (mac, requestURI, reqMethod, reqContentType, reqBody) {
  var u = new url.URL(requestURI);
  var path = u.pathname;
  var search = u.search;
  var host = u.host;
  var port = u.port;

  var access = reqMethod.toUpperCase() + ' ' + path;
  if (search) {
    access += search;
  }
  // add host
  access += '\nHost: ' + host;
  // add port
  if (port) {
    access += ':' + port;
  }

  // add content type
  if (reqContentType && (reqContentType === 'application/json' || reqContentType === 'application/x-www-form-urlencoded')) {
    access += '\nContent-Type: ' + reqContentType;
  }

  access += '\n\n';

  // add reqbody
  if (reqBody) {
    access += reqBody;
  }

  // console.log(access);

  var digest = exports.hmacSha1(access, mac.secretKey);
  var safeDigest = exports.base64ToUrlSafe(digest);
  return 'Qiniu ' + mac.accessKey + ':' + safeDigest;
};



邮件

邮件的话使用到了【彩虹屁的夸人接口】和好123的天气接口;可以自己随意发挥;效果如下图:

image.png

发送邮件方法封装

const nodemailer = require("nodemailer");
// 
/**
 * 发送邮件函数
 * @params {
 *   to: 对方邮箱,
 *   subject: 主题,
 *   text:邮件内容
 * }
 *
 * return: 布尔值
 */
async function sendMail(p) {
  var user = "xxx@qq.com";//自己的邮箱
  var pass = "xxx"; //qq邮箱授权码;百度一下怎么获得即可;很简单;QQ邮箱-设置-mtp服务

  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: p.to, // list of receivers
    subject: p.subject, // Subject line
    text: p.text, // plain text body
  });
  console.log("邮件发送成功:" + info.response);
  return info
}

module.exports = {
  sendMail
}

使用定时任务每天早上7点半自动发送邮件提醒

const schedule = require("node-schedule");
const qiniu = require('qiniu')
const axios = require('axios')
const { sendMail } = require('./email')

let sendWeather = async a => {
  let getWeather = async cityId => {
    let weather = await axios.get('https://www.weatherol.cn/api/home/getCurrAnd15dAnd24h?cityid=' + cityId)
    let info = await axios.get('https://www.weatherol.cn/api/home/getSunMoonAndIndex?cityid=' + cityId)
    return {
      weather: weather.data,
      info: info.data
    }
  }


  let rule = '30 7 * * *'
  let key = 'sendWeather'
  if (schedule.scheduledJobs[key]) {
    schedule.scheduledJobs[key].cancel(); //先取消,然后重启
  }

  schedule.scheduleJob(key, rule, function () {
    send()
  });

  async function send() {
    {
      // 广州101280109
      let { weather, info } = await getWeather(101280109)
      let current = weather.data.current
      let t = info.data.index

      let 彩虹屁 = await axios.get('https://chp.shadiao.app/api.php')
      if (weather.code == 200 && info.code == 200) {
        let text = `
        ${current.nongLi}-天气:${current.current.weather} 当前温度:${current.current.temperature}度 \n
        风力:${current.current.winddir + current.current.windpower} \n
        ---
        ${t[2].index_type_ch}${t[2].index_content} \n
        ${t[5].index_type_ch}${t[5].index_content} \n
        ${t[4].index_type_ch}${t[4].index_content} \n \n

        ${current.tips} \n
        ${彩虹屁.data}😯😯😯
        `

        sendMail({
          to: `<xx@qq.com>`,
          subject: '早xxx,今日天气提醒!',
          text
        })
      } 
    }


  }

}

感兴趣的小伙伴,自己试试吧;记得点个赞哦😯