nodejs发送邮件验证码封装(express框架)以QQ邮箱为例

一、下载nodemailer

npm i nodemailer -s

二、做个js文件,封装发送邮件函数

// 发送邮箱验证码配置
//引入模块
const nodemailer = require('nodemailer');

let sendMails = (mailId, VerificationCode) => {
    //设置邮箱配置
    let transporter = nodemailer.createTransport({
        //host:'smtp.qq.com',    //邮箱服务的主机,如smtp.qq.com
        service: 'qq',
        port: '465',                //对应的端口号QQ邮箱的端口号是465
        secure: false,              //开启安全连接
        //secureConnection:false,   //是否使用ssl
        auth: {                              //用户信息
            user: '8*******[email protected]',        //用来发邮件的邮箱账户
            pass: 'xxxxxxxxxxxxxxx'         //这里的密码是qq的smtp授权码,可以去qq邮箱后台开通查看
        }
    });

    //设置收件人信息
    let mailOptions = {
        from: '8*******[email protected]',           //谁发的
        to: mailId,                         //发给谁
        subject: 'DailyWriter验证码为' + VerificationCode,  //主题是什么
        text: '验证码邮件',                //文本内容
        html: '',//html模板
        // attachments: [              //附件信息,如果需要了再打开使用
        //     {
        //         filename: '',
        //         path: '',
        //     }
        // ]
    };

    return new Promise((resolve, reject) => {       //异步函数
        //发送邮件
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) { 
                reject(error)       //错误
            } else {
                resolve(info)
                // console.log(`信息id   Message: ${info.messageId}`);  
                // console.log(`成功响应 sent: ${info.response}`); 
                // console.log(`邮件信息 mailOptions: ${JSON.stringify(mailOptions)}`); 
            }
        });
    })
}

// export default sendMails  暴露出去
module.exports = {
    sendMails
}

三、需要使用的地方进行调用

router.post('/register', async (req, res, next) => {
  //测试邮件
  let mailId = 'xxxxxx'                //收件人的邮箱账号
  let VerificationCode = '8888'        //四位验证码,随机码下面有封装,直接调用即可
//  let VerificationCode = getVerificationCode()        //生成随机码
//  console.log('发送的验证码为:'+ VerificationCode)   //查看随机码
  sendMails(mailId, VerificationCode).then(res => {
    // console.log(res, '返回的数据');
    if (res.response == '250 OK: queued as.') {             //如果发送成功执行的操作
      console.log('发送成功了,收件人是:'+res.accepted)    //是个数组
    } else {    //发送失败执行的操作
      console.log('发送失败了,错误为:'+res.rejected)      //也是个数组
    }
  })
  return
});

四、附加   四位随机验证码生成封装

let getVerificationCode = (codeLength = 4) => { //传入需要的字符串长度,不传默认为4
  // 准备一个用来抽取码的字符串,或者字典
  // let verification_code_str = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  //数字和字母
  let verification_code_str = "0123456789";     //纯数字
  // 获取某个范围的随机整数,封装的函数,在上面抽取字典的时候进行了调用
  function getRandom(min, max) {                 //意思是获取min-max数字之间的某个随机数,直接调用即可
    return Math.round(Math.random() * (max - min) + min);
  }
  let newStr = '';                    //创建一个空字符串,用来拼接四位随机码
  for (var i = 0; i < codeLength; i++) {       //for循环四次,则拼接四次随机码
    newStr += verification_code_str[getRandom(0, verification_code_str.length - 1)];   //从字典中随机选一个下标,并拼接到空字符串中
  }
  return newStr
}


//调用
let mycode = getVerificationCode()  //可以不传值,默认为4位随机码
console.log('生成的随机码为:' + mycode)

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>