600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > nodejs发送邮件验证码封装(express框架)以QQ邮箱为例

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

时间:2019-06-29 12:17:52

相关推荐

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

一、下载nodemailer

npm i nodemailer -s

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

// 发送邮箱验证码配置//引入模块const nodemailer = require('nodemailer');let sendMails = (mailId, VerificationCode) => {//设置邮箱配置let transporter = nodemailer.createTransport({//host:'', //邮箱服务的主机,如service: 'qq',port: '465',//对应的端口号QQ邮箱的端口号是465secure: false, //开启安全连接//secureConnection:false, //是否使用sslauth: {//用户信息user: '8*******3@', //用来发邮件的邮箱账户pass: 'xxxxxxxxxxxxxxx' //这里的密码是qq的smtp授权码,可以去qq邮箱后台开通查看}});//设置收件人信息let mailOptions = {from: '8*******3@', //谁发的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)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。