天天看點

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
    }
}
           

繼續閱讀