1、前言
开发个人网站时,注册页面可以使用邮箱验证,于是记录一下如何用nodejs/express服务器实现邮箱发送验证码,不仅可以在邮箱注册时使用,还可以拓展用于各种安全验证。
2、依赖包
nodejs服务器需要 express,另外就是我们发送邮箱的包 nodemailer , cors解决跨域用于测试
npm i express nodemailer cors
3、使用qq邮箱获取授权码
1)首先封装 nodemailer.js 文件,添加基本配置,配置前需要得到邮箱类型的 port 和 secure 还有 邮箱stmp授权码。
2)//node_modules/nodemailer/lib/well-known/services.json 可以查看相关的配置,比如这里是qq邮箱,port为465,secure为true。
3)邮箱---设置--账户--POP3/SMTP服务---开启---获取stmp授权码
最终获取到授权码
4、代码实现
1)创建nodemailer.js文件
const nodemailer = require('nodemailer')
let nodeMail = nodemailer.createTransport({
service: "qq", //类型qq邮箱
port: 465, //上文获取的port
secure: true, //上文获取的secure
auth: {
user: "779217162@qq.com", // 发送方的邮箱,可以选择你自己的qq邮箱
pass: "上文获取的stmp授权码", // 上文获取的stmp授权码
},
});
module.exports = nodeMail
2)创建app.js
//app.js
const express = require("express");
const cors = require("cors");
const nodeMail = require("./nodemailer.js");
const app = express();
app.use(express.static("public"));
app.use(express.json());
app.use(cors());
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: `"faker前端开发"<779217162@qq.com>`, // 发件人
subject: "验证码", //邮箱主题
to: email, //收件人,这里由post请求传递过来
// 邮件内容,用html格式编写
html: `
<p>您好!</p>
<p>您的验证码是:<strong style="color:orangered;">${code}</strong></p>
<p>如果不是您本人操作,请无视此邮件</p>
`,
};
await nodeMail.sendMail(mail, (err, info) => {
if (!err) {
res.json({ msg: "验证码发送成功" });
} else {
res.json({ msg: "验证码发送失败,请稍后重试" });
}
});
});
app.listen(3123, () => {
console.log("服务开启成功 , http:www.localhost:3123");
});
3)创建/public/index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>发送邮件</title>
</head>
<body>
<button onclick="sendMail()">发送邮件</button>
<script>
async function sendMail() {
console.log("发送邮件");
const res = await fetch("/api/email", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: "991584844@qq.com",
}),
});
const data = await res.json();
console.log(data);
}
</script>
</body>
</html>
目录结构为:
5、发送效果
发送邮件: 779217162@qq.com ===> 991584844@qq.com
6、源码地址
github: github.com/ArcherNull/…
完结撒花。。。