天天看点

node koa发送邮箱验证码

1. 注册一个邮箱

开启

POP3/SMTP/IMAP

node koa发送邮箱验证码

下方代码内的auth.pass = '下图授权码’

node koa发送邮箱验证码

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

const nodemailer = require('nodemailer')

const userEmail = '[email protected]'
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
    }
}
           

继续阅读