栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

nodejs/express 实现邮箱发送验证码

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

nodejs/express 实现邮箱发送验证码

前言

开发个人网站时,注册页面可以使用邮箱验证,于是记录一下如何用nodejs/express服务器实现邮箱发送验证码,不仅可以在邮箱注册时使用,还可以拓展用于各种安全验证。 依赖包

nodejs服务器需要express,另外就是我们发送邮箱的包nodemailer

npm i express nodemailer
nodejs服务端代码

    首先封装nodemailer.js文件,添加基本配置,配置前需要得到邮箱类型的port和secure还有邮箱stmp授权码。

    //node_modules/nodemailer/lib/well-known/services.json可以查看相关的配置,比如这里是qq邮箱,port为465,secure为true。

    邮箱—设置–账户–POP3/SMTP服务—开启—获取stmp授权码

    //nodemailer.js
    import nodemailer from 'nodemailer'
    
    let nodeMail = nodemailer.createTransport({
        service: 'qq', //类型qq邮箱
        port: 465,//上文获取的port
        secure: true,//上文获取的secure
        auth: {
            user: 'xxxxx@qq.com', // 发送方的邮箱,可以选择你自己的qq邮箱
            pass: 'xxxxxxxx' // 上文获取的stmp授权码
        }
    });
    
    export default nodeMail
    

    引入写好的nodemailer.js完成nodejs服务器app.js,掌握发送邮件对象mail的各种属性。

    //app.js
    import express from 'express'
    import nodeMail from './nodemailer.js'
    
    const app = express()
    app.use(express.json())
    
    app.post('/api/email', async (req, res) => {
        const email = req.body.email
        const code = String(Math.floor(Math.random() * 1000000)).padEnd(6, '0') //生成6位随机验证码
        //发送邮件
        const mail = {
            from: `"月亮前端开发"`,// 发件人
            subject: '验证码',//邮箱主题
            to: email,//收件人,这里由post请求传递过来
            // 邮件内容,用html格式编写
            html: `
                

    您好!

    您的验证码是:${code}

    如果不是您本人操作,请无视此邮件

    ` }; await nodeMail.sendMail(mail, (err, info) => { if (!err) { res.json({msg: "验证码发送成功"}) } else { res.json({msg: "验证码发送失败,请稍后重试"}) } }) }); app.listen(3000, () => { console.log("服务开启成功"); })
前端代码测试






转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/751013.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号