node koa发送邮箱验证码

1. 注册一个邮箱

开启POP3/SMTP/IMAP
在这里插入图片描述

下方代码内的auth.pass = '下图授权码’
在这里插入图片描述

2. nodejs koa发送邮箱验证码:

const nodemailer = require('nodemailer')

const userEmail = 'xxxx@163.com'
const transporter = nodemailer.createTransport({
  service: '163',
  secureConnection: true,
  auth: {
    user: userEmail,
    pass: 'MBZYT***OJMKO'  //这个是开启`POP3/SMTP/IMAP`的授权码
  }
})

router.get('/sendcode', async ctx => {
    const email = ctx.query.email
    // 记得检测该 email 是否已注册
    const code = Math.random().toString().slice(2,6)
    ctx.session.emailcode = code //随机验证码
	const mailOptions = {
      from: userEmail,
      cc: userEmail,
      to: email,
      subject: '验证码',
      text: '说明内容',
      html: '<h2>【小米官方】</h2>验证码:<span>${code}</span>'
    }
	try {
      await transporter.sendMail(mailOptions)
      ctx.body = {
	      code: 0,
	      message: '邮箱验证码发送成功!',
	  }
    } catch(e) {
	  ctx.body = {
	      code: -1,
	      message: '邮箱验证码发送失败!',
	  }
    }
})

// 登录时判断验证码是否一致即可
router.post('/login', async ctx => {
	const { email, emailcode } = ctx.request.body
    if (emailcode !== ctx.session.emailcode) {
      ctx.body = {
	      code: -1,
	      message: '邮箱验证码错误!',
	  }
      return
    }
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值