node.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > node.js > node发送验证码到邮箱

node 使用 nodemailer工具发送验证码到邮箱

作者:哇伊卡

最近闲着没事,我就在练习使用node和mysql编写接口,计划写一个完整的vue系统,这篇文章主要介绍了node 使用 nodemailer工具发送验证码到邮箱,需要的朋友可以参考下

最近闲着没事,我就在练习使用node和mysql编写接口,计划写一个完整的vue系统。刚刚处理完注册登录的功能,我决定加入验证码验证。在思考是否使用手机号或邮箱验证时,最终我选择了将验证码发送到邮箱。于是我发现了一个非常有用的工具——nodemailer。

功能

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服务,

![image.png](https://img-blog.csdnimg.cn/img_convert/2fd1e05b4c7dea4b3d5a8ec487588274.png

开启服务,按照指示即可获取。

设置收件人:

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发送验证码到邮箱内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文