node实现定时发送邮件的示例代码

时间:2019-03-31
本文章向大家介绍node实现定时发送邮件的示例代码,主要包括node实现定时发送邮件的示例代码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文介绍了node实现定时发送邮件的示例代码,分享给大家,具体如下:

定时发送,可做提醒使用

nodemailer

nodemailer 是一款简单易用的基于于SMTP协议(或 Amazon SES)的邮件发送组件

cron

cron可以指定每隔一段时间执行指定的程序、也可以指定每天的某个时刻执行某个程序、还可以按照星期、月份来指定。

npm install nodemailer -S
npm install nodemailer-smtp-transport -S
npm install cron -S

代码中有详细的注释(同时希望大家在平时写代码的时候养成写注释的习惯)

let nodemailer = require('nodemailer'),
  smtpTransport = require('nodemailer-smtp-transport'),
  cronJob = require('cron').CronJob;

// SMTP 连接
let transport = nodemailer.createTransport(smtpTransport({
 // 主机
 host: 'smtp.163.com',
 // 是否使用 SSL
 secure: false,
 secureConnection: false,
 // 网易的SMTP端口
 port: 25, 
 auth: {
  // 账号
  user: '***@163.com', 
  // 授权码(自行百度邮箱SMTP的授权码设置),此处非密码
  pass: '***', 
 }
}));
// 设置邮件内容
let mailOptions = {
 // 发件人地址,例如 1234<1234@163.com>
 from: '***<***@163.com>', 
 // 收件人地址,可以使用逗号隔开添加多个
 // '***@qq.com, ***@163.com'
 to: '***@qq.com', 
 // 标题
 subject: 'Hello World', 
 // 邮件内容可以自定义样式
 html: '<strong style="color: red">测试"邮件轰炸机"</strong>'
}
// 定时发送邮件
// 每秒执行一次
// 具体的各项设置查看上方的链接
new cronJob('* * * * * *', () => {
 transport.sendMail(mailOptions, (error, response) => {
  if (error) {
   console.error(error)
  } else {
   console.log('Message Send Ok')
  }
  // 记得关闭连接
  transport.close();
 })
}, null, true, 'Asia/Shanghai');

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。