nodejs實現(xiàn)郵箱發(fā)送驗證碼功能
1、前言
開發(fā)個人網(wǎng)站時,注冊頁面可以使用郵箱驗證,于是記錄一下如何用nodejs/express服務器實現(xiàn)郵箱發(fā)送驗證碼,不僅可以在郵箱注冊時使用,還可以拓展用于各種安全驗證。
2、依賴包
nodejs服務器需要 express,另外就是我們發(fā)送郵箱的包 nodemailer , cors解決跨域用于測試
npm i express nodemailer cors
3、使用qq郵箱獲取授權碼
1)首先封裝 nodemailer.js 文件,添加基本配置,配置前需要得到郵箱類型的 port 和 secure 還有 郵箱stmp授權碼。
2)//node_modules/nodemailer/lib/well-known/services.json 可以查看相關的配置,比如這里是qq郵箱,port為465,secure為true。
3)郵箱---設置--賬戶--POP3/SMTP服務---開啟---獲取stmp授權碼
最終獲取到授權碼
4、代碼實現(xiàn)
1)創(chuàng)建nodemailer.js文件
const nodemailer = require('nodemailer') let nodeMail = nodemailer.createTransport({ service: "qq", //類型qq郵箱 port: 465, //上文獲取的port secure: true, //上文獲取的secure auth: { user: "779217162@qq.com", // 發(fā)送方的郵箱,可以選擇你自己的qq郵箱 pass: "上文獲取的stmp授權碼", // 上文獲取的stmp授權碼 }, }); module.exports = nodeMail
2)創(chuàng)建app.js
//app.js const express = require("express"); const cors = require("cors"); const nodeMail = require("./nodemailer.js"); const app = express(); app.use(express.static("public")); app.use(express.json()); app.use(cors()); app.post("/api/email", async (req, res) => { const email = req.body.email; const code = String(Math.floor(Math.random() * 1000000)).padEnd(6, "0"); //生成6位隨機驗證碼 //發(fā)送郵件 const mail = { from: `"faker前端開發(fā)"<779217162@qq.com>`, // 發(fā)件人 subject: "驗證碼", //郵箱主題 to: email, //收件人,這里由post請求傳遞過來 // 郵件內(nèi)容,用html格式編寫 html: ` <p>您好!</p> <p>您的驗證碼是:<strong style="color:orangered;">$[code]</strong></p> <p>如果不是您本人操作,請無視此郵件</p> `, }; await nodeMail.sendMail(mail, (err, info) => { if (!err) { res.json({ msg: "驗證碼發(fā)送成功" }); } else { res.json({ msg: "驗證碼發(fā)送失敗,請稍后重試" }); } }); }); app.listen(3123, () => { console.log("服務開啟成功 , http:www.localhost:3123"); });
3)創(chuàng)建/public/index.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>發(fā)送郵件</title> </head> <body> <button onclick="sendMail()">發(fā)送郵件</button> <script> async function sendMail() { console.log("發(fā)送郵件"); const res = await fetch("/api/email", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email: "991584844@qq.com", }), }); const data = await res.json(); console.log(data); } </script> </body> </html>
目錄結構為:
5、發(fā)送效果
發(fā)送郵件: 779217162@qq.com ===> 991584844@qq.com
6、源碼地址
github: https://github.com/ArcherNull/Archer/tree/main/nodejs-mailer
以上就是nodejs實現(xiàn)郵箱發(fā)送驗證碼功能的詳細內(nèi)容,更多關于nodejs郵箱發(fā)送驗證碼的資料請關注腳本之家其它相關文章!
相關文章
nodejs中art-template模板語法的引入及沖突解決方案
本篇文章主要介紹了nodejs中art-template模板語法的引入及沖突解決方案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11如何在node.js中使用?JsonWebToken模塊進行token加密
目前在web框架中最流行的身份驗證是使用jsonwebtoken,簡稱jwt.可以設置加密方式,過期時間,存放個人信息,逆解析,下面這篇文章主要給大家介紹了關于如何在node.js中使用?JsonWebToken模塊進行token加密的相關資料,需要的朋友可以參考下2023-03-03nodejs入門教程二:創(chuàng)建一個簡單應用示例
這篇文章主要介紹了nodejs入門教程之創(chuàng)建一個簡單應用的方法,涉及nodejs http模塊的引用、端口監(jiān)聽等相關操作技巧,需要的朋友可以參考下2017-04-04