Nodejs 中使用 nodemailer 包 实现邮箱验证
安装
npm install nodemailer
引入
const nodemailer = require("nodemailer");
使用 express搭建的服务 举个例子
// 发送验证码 http://localhost:9000/getcode
app.get('/getcode', (req, res) => {
let code = Math.floor(Math.random() * 900000) + 100000; //随机生成 6位数的验证码
// 建立一个smtp连接
let transporter = nodemailer.createTransport({
host: 'smtp.qq.com', // 端口 这里是QQ邮箱 网易邮箱为 smtp.163.com
// secure: true, // 是否使用TLS,true,端口为465,否则其他或者568
secureConnection: true, //安全的发邮件 使用了 SSL
port: 465, // SMTP端口
auth: {
user: '480237979@qq.com', //你自己的邮箱
pass: '' // 不是qq密码,是POP3/SMTP服务授权码(下面有链接教程)
},
rejectUnauthorized: false
});
// 配置相关参数
let options = {
from: '480237979@qq.com', //发件人地址(可直接填发件人的邮箱)
to: `480237979@qq.com`, //接收者名单(多个以逗号分隔)
subject: '欢迎使用', // 邮件内容标题
//text: `验证码为:${code}`,// 发送text文本格式的内容
html: `<h1>验证码为:${code}</h1>` //html格式的内容
};
transporter.sendMail(options, (err, msg) => {
if (err) {
console.log(err)
}else {
console.log('发送成功')
transporter.close //关闭连接
}
});
})
POP3/SMTP服务授权码教程 https://jingyan.baidu.com/article/425e69e61e9178be15fc168a.html