node 使用 nodemailer工具发送验证码到邮箱
作者:哇伊卡
最近闲着没事,我就在练习使用node和mysql编写接口,计划写一个完整的vue系统,这篇文章主要介绍了node 使用 nodemailer工具发送验证码到邮箱,需要的朋友可以参考下
最近闲着没事,我就在练习使用node和mysql编写接口,计划写一个完整的vue系统。刚刚处理完注册登录的功能,我决定加入验证码验证。在思考是否使用手机号或邮箱验证时,最终我选择了将验证码发送到邮箱。于是我发现了一个非常有用的工具——nodemailer。
功能
- 零依赖性的单个模块–由于没有死角,因此代码易于审核
- 高度重视安全性
- Unicode 支持使用任何字符,包括表情符号
- Windows 支持 –您可以使用 npm在 Windows 上,就像其他模块一样,没有编译的依赖项。从 Azure 或 Windows 盒子免费使用它
- 使用 HTML 内容以及纯文本替代
- 加 附件 到消息
- 嵌入式的 HTML 内容的图像附件–您的设计不会被阻塞
- 使用 TLS / STARTTLS 的安全电子邮件传递
- 不同 运输方式 除了内置 SMTP 支持
- 与签署消息 DKIM
- 自订 插件支持 用于处理消息
- OAuth2 认证方式
- 代理人 用于 SMTP 连接
- ES6 码 - 没有更多的无意内存泄漏,由于吊装 VAR 的
- 来自的自动生成的电子邮件测试帐户电子邮件
1.先下nodemailer载依赖
npm i nodemailer 或 yarn add nodemailer
2.在utils文件下创建sendEmail.js,引入nodemailer模块
const nodemailer = require('nodemailer')创建一个SMTP客户端配置对象:
nodemailer.createTransport({
host: "smtp.qq.com", // 邮箱服务的host,我使用的是QQ邮箱
port: 465,
secure: true,
auth: {
user: 'XXX@qq.com', 发送邮件的邮箱
pass: '邮箱授权码'
}
});邮箱授权码获取:
登录qq邮箱-》点击设置,找到账户,下滑找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,

开启服务,按照指示即可获取。
设置收件人:
mailOptions = {
from: '来自XX<XXX@qq.com>', //发送邮件的邮箱信息
to: toEmail, // 发送给谁的邮箱
subject: "验证码", // 标题
// text: `你的验证码为XXX,3分钟内有效,请务透漏给他人`,//发送文本
html: "你的验证码为<b style='color:skybkue;'>" + XXX + "</b>,3分钟内有效,请务透漏给他人!",
}调用transporter.sendMail发送邮件:
transporter.sendMail(mailOptions)
完整代码
sendEmail.js =>
const nodemailer = require('nodemailer')
const sendEmail = (toEmail, sendText, host = 'smtp.qq.com') => {
return new Promise((resolve, reject) => {
let transporter = nodemailer.createTransport({
host: host,
port: 465,
// 开启安全连接,这个开不开都可以,对安全性有要求的话,最好开启
secureConnection: true,
auth: {
user: 'XXX@qq.com',
pass: '邮箱授权码',
},
tls: {
rejectUnauthorized: false, // 拒绝认证就行了, 不然会报证书问题
},
});
const mailOptions = {
from: '来自XXX<XXX@qq.com>',
to: toEmail,
subject: "验证码",
html: "你的验证码为<b style='color:skybkue;'>" + sendText + "</b>,3分钟内有效,请务透漏给他人!",
}
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
reject(error);
} else {
resolve(info)
}
})
})
}
module.exports = {
sendEmail
}调用sendEmail获取验证码接口 =>:
const { sendEmail } = require("../utils/sendEmail");
/*email 邮箱账户 passWord 密码 verification_code 验证码 code_expires 验证码有效期 code_effective 验证码是否有效 (0 无效 ;1 有效 */
exports.GetCaptcha = async (req, res) => {
try {
const isExit = await resSql('SHOW TABLES LIKE "userAccount"');
if (!isExit.length) {
await resSql(
`CREATE TABLE userAccount(email VARCHAR(50) NOT NULL,passWord VARCHAR(255),verification_code INT(10),code_expires VARCHAR(255),code_effective TINYINT(1) DEFAULT 0,PRIMARY KEY (email))`
);
}
// 发送验证码到邮箱
// console.log('=========检测邮箱格式=======');
const { email } = req.body;
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
res.json({
code: 500,
message: "错误的邮箱格式",
});
return;
}
// 设置验证码
let verification_code = "";
for (let i = 0; i < 6; i++) {
verification_code += parseInt(Math.random() * 10);
}
const now_timestamp = moment().format("x");
// 验证码3min内有效
const code_expires = `${Number(now_timestamp) + 180000}`;
// 查询email是否存在
const isExitEmail = await resSql(
`SELECT * FROM userAccount WHERE email='${email}'`
);
// 插入
let sendCodeSql = `INSERT INTO userAccount (email, verification_code, code_expires, code_effective) VALUES ("${email}", "${verification_code}", "${code_expires}", 1)`;
if (isExitEmail.length) {
// 存在就修改
sendCodeSql = `UPDATE userAccount SET verification_code='${verification_code}', code_expires='${code_expires}', code_effective=1 WHERE email='${email}'`;
}
sendEmail(email, verification_code)
.then(async () => {
try {
await resSql(sendCodeSql);
res.json({
code: 200,
message: "发送成功!验证码3分钟内有效",
});
} catch (error) {
res.json({
code: 500,
message: error,
});
}
})
.catch((err) => {
res.json({
code: 500,
message: err || "发送失败",
});
});
} catch (error) {
res.json({
code: 500,
message: error || "错误返回",
});
}
};到此这篇关于node 使用 nodemailer 发送验证码到邮箱的文章就介绍到这了,更多相关node发送验证码到邮箱内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
