天天看點

NodeJs實作郵箱驗證

要想實作發送郵件功能,主要是運用

nodemailer

這個依賴包,官網位址:https://nodemailer.com/about/

utils.js 代碼:

module.exports = {
      mail
}

/**
 * 發送郵件
 * @param {string} to 收件方郵箱
 * @param {string} title 内容标題
 * @param {string} content 郵件内容
 * @param {Function} callback 回調函數(内置參數)
 * 
 */
function mail(to,title,content,callback) {
    const nodemailer = require('nodemailer'); //引入依賴
    /**
     * 詳細配置檔案位址: node_modules/lib/well-known/services
     */
    let transporter = nodemailer.createTransport({
        host: 'smtp.163.com',
        port: 465,
        secure: true,
        auth: {
            user: '[email protected]', //發送方郵箱
            pass: 'xxx' //發送方郵箱的授權碼,一般去郵箱設定裡面找,應該可以找到
        }
    });

    let info = {
        from: '[email protected]',//發送方郵箱
        to: to, 
        subject: title,
        text: content
         //html: '<h1>這裡内容</h1>',text和html任選其一即可
    }
      //發送郵件
    transporter.sendMail(info,(err,data) => {
        callback &&  callback(err,data)
    })
}

           

NodeJs代碼:

const http = require('http');
const path = require('path');
const fs = require('fs');
const url = require('url');
const utils = require(path.resolve(__dirname,'./utils.js'));
let time = null; //全局存儲時間戳
let code = null; //全局存儲驗證碼
const server = http.createServer(function (req,res) {
    if (req.url == '/') {
        fs.readFile('./index.html','utf8',function (err,data) {
            res.writeHead(200,{'Content-type': 'text/html'});
            if (err) {
                res.write('檔案讀取錯誤!');
            } else {
                res.write(data);
            }
            res.end();
        })
    }
    
    if (url.parse(req.url).pathname == '/date') {
        let query = url.parse(req.url,true).query;
        let mail = query.mail; //擷取前端傳遞的郵箱資訊

        code = Math.floor(Math.random() * 1000); //存入驗證碼
        time = new Date().getTime(); //存入發送驗證碼的時間戳

        utils.mail(mail,'驗證碼',code + '',function (err,data) {
            res.writeHead(200);
            if (err) {
                res.write('驗證碼發送失敗')
            } else {
                res.write('驗證碼發送成功')
            }
            res.end();
        });
    }  
    if (url.parse(req.url).pathname == '/code') {
        let query = url.parse(req.url,true).query;
        let cd = query.code; //傳遞使用者輸入的驗證碼
        let ct = query.time; //傳遞使用者點選送出驗證碼的時間戳

        res.writeHead(200);
        console.log('code:' + code,'cd:' + cd, 'time:' + time, 'ct:' + ct)
        //判斷是否超過規定時間
        if (ct - time >= 1 * 60 * 1000) {
            res.write('驗證碼已過期')
        } else {
            if (cd == code) {
                res.write('驗證通過')
            } else {
                res.write('驗證碼錯誤')
            }
        }
        res.end();
    }

});




server.listen('80','localhost',() => {
    console.log('start server!');
})




           

html代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>郵箱注冊驗證</title>
    <script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
    <input type="text" placeholder="請輸入郵箱" class="input">
    <button class="sendCode">發送驗證碼</button>
    <input type="text" placeholder="郵箱驗證碼" class="code">
    <button class="btn">送出</button>
    <script>
        var inp = document.getElementsByClassName('input')[0];
        var code = document.getElementsByClassName('code')[0];
        var btn = document.getElementsByClassName('btn')[0];
        var sendCode = document.getElementsByClassName('sendCode')[0];

        sendCode.onclick = function () {
            console.log('發送驗證碼');
            $.ajax({
                url: 'http://localhost/date',
                async: false,
                data: {
                    mail: inp.value
                },
                success: function (res) {
                    console.log(res);
                },
                error: function (err) {
                    console.log(err);
                }
            })
        }

        //送出驗證碼
        btn.onclick = function () {
           $.ajax({
            url: 'http://localhost/code',
                async: false,
                data: {
                    code: code.value,
                    time: new Date().getTime()
                },
                success: function (res) {
                    console.log(res);
                },
                error: function (err) {
                    console.log(err);
                }
           })
        }

    </script>
</body>
</html>

           

目錄結構

'|-- 郵箱驗證',
  '    |-- index.html',
  '    |-- index.js',
  '    |-- package-lock.json',
  '    |-- utils.js',