脚本宝典收集整理的这篇文章主要介绍了nodejs发送邮件验证码封装(express框架)以QQ邮箱为例,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
npm i nodemailer -s
// 发送邮箱验证码配置
//引入模块
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*******3@qq.com', //用来发邮件的邮箱账户
pass: 'xxxxxxxxxxxxxxx' //这里的密码是qq的smtp授权码,可以去qq邮箱后台开通查看
}
});
//设置收件人信息
let mailOptions = {
from: '8*******3@qq.com', //谁发的
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)
以上是脚本宝典为你收集整理的nodejs发送邮件验证码封装(express框架)以QQ邮箱为例全部内容,希望文章能够帮你解决nodejs发送邮件验证码封装(express框架)以QQ邮箱为例所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。