开发个人网站时,注册页面可以使用邮箱验证,于是记录一下如何用nodejs/express服务器实现邮箱发送验证码,不仅可以在邮箱注册时使用,还可以拓展用于各种安全验证。 依赖包
nodejs服务器需要express,另外就是我们发送邮箱的包nodemailer
npm i express nodemailernodejs服务端代码
首先封装nodemailer.js文件,添加基本配置,配置前需要得到邮箱类型的port和secure还有邮箱stmp授权码。
//node_modules/nodemailer/lib/well-known/services.json可以查看相关的配置,比如这里是qq邮箱,port为465,secure为true。
邮箱—设置–账户–POP3/SMTP服务—开启—获取stmp授权码
//nodemailer.js
import nodemailer from 'nodemailer'
let nodeMail = nodemailer.createTransport({
service: 'qq', //类型qq邮箱
port: 465,//上文获取的port
secure: true,//上文获取的secure
auth: {
user: 'xxxxx@qq.com', // 发送方的邮箱,可以选择你自己的qq邮箱
pass: 'xxxxxxxx' // 上文获取的stmp授权码
}
});
export default nodeMail
引入写好的nodemailer.js完成nodejs服务器app.js,掌握发送邮件对象mail的各种属性。
//app.js
import express from 'express'
import nodeMail from './nodemailer.js'
const app = express()
app.use(express.json())
app.post('/api/email', async (req, res) => {
const email = req.body.email
const code = String(Math.floor(Math.random() * 1000000)).padEnd(6, '0') //生成6位随机验证码
//发送邮件
const mail = {
from: `"月亮前端开发"`,// 发件人
subject: '验证码',//邮箱主题
to: email,//收件人,这里由post请求传递过来
// 邮件内容,用html格式编写
html: `
您好!
您的验证码是:${code}
如果不是您本人操作,请无视此邮件
`
};
await nodeMail.sendMail(mail, (err, info) => {
if (!err) {
res.json({msg: "验证码发送成功"})
} else {
res.json({msg: "验证码发送失败,请稍后重试"})
}
})
});
app.listen(3000, () => {
console.log("服务开启成功");
})



