美文网首页
Nodejs+koa+redis+nodemailer 实现发送

Nodejs+koa+redis+nodemailer 实现发送

作者: Poppy11 | 来源:发表于2020-09-17 15:33 被阅读0次

一、首先安装依赖

npm install redis --save
npm install nodemailer --save

二、单独写nodemailer模块,暴露出去

//nodemailer.js
const nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
    //node_modules/nodemailer/lib/well-known/services.json  查看相关的配置,如果使用qq邮箱,就查看qq邮箱的相关配置
    service: 'qq', //类型qq邮箱
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
        user: '邮箱', //注册的邮箱账号
        pass: '授权码' //邮箱的授权码,不是注册时的密码,等你开启的stmp服务自然就会知道了
    }
});
//pass 不是邮箱账户的密码而是stmp的授权码(必须是相应邮箱的stmp授权码)
//邮箱---设置--账户--POP3/SMTP服务---开启---获取stmp授权码

module.exports = function (user,code){
    const {username,password,email} = user
    let mailOptions = {
        from: '"知道团队" <785820791@qq.com>', // 发送方
        to: email, //接收者邮箱,多个邮箱用逗号间隔
        subject: `欢迎来到"知道",你的验证码(${code})`, // 标题
        html:`<head><base target="_blank" /><style type="text/css">::-webkit-scrollbar{ display: none; }</style><style id="cloudAttachStyle" type="text/css">#divNeteaseBigAttach, #divNeteaseBigAttach_bak{display:none;}</style><style id="blockquoteStyle" type="text/css">blockquote{display:none;}</style><style type="text/css">     body{font-size:14px;font-family:arial,verdana,sans-serif;line-height:1.666;padding:0;margin:0;overflow:auto;white-space:normal;word-wrap:break-word;min-height:100px}  td, input, button, select, body{font-family:Helvetica, \'Microsoft Yahei\', verdana}  pre {white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;width:95%}  th,td{font-family:arial,verdana,sans-serif;line-height:1.666} img{ border:0}  header,footer,section,aside,article,nav,hgroup,figure,figcaption{display:block}  blockquote{margin-right:0px}</style></head><body tabindex="0" role="listitem"><table width="700" border="0" align="center" cellspacing="0" style="width:700px;"><tbody><tr><td><div style="width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;"><table border="0" cellpadding="0" cellspacing="0" width="700" height="39" style="font:12px Tahoma, Arial, 宋体;"><tbody><tr><td width="210"></td></tr></tbody></table></div><div style="width:680px;padding:0 10px;margin:0 auto;"><div style="line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;"><strong style="display:block;margin-bottom:15px;">尊敬的用户:${username}<span style="color:#f60;font-size: 16px;"></span>您好!</strong><strong style="display:block;margin-bottom:15px;">您正在进行<span style="color: red">注册账号</span>操作,请在验证码输入框中输入:<span style="color:#f60;font-size: 24px">${code}</span>,以完成操作。</strong></div>     <div style="margin-bottom:30px;"><small style="display:block;margin-bottom:20px;font-size:12px;"><p style="color:#747474;">     注意:此操作可能会修改您的密码、登录邮箱或绑定手机。如非本人操作,请及时登录并修改密码以保证帐户安全<br>(工作人员不会向你索取此验证码,请勿泄漏!)</p></small></div></div><div style="width:700px;margin:0 auto;"><div style="padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;"><p>此为系统邮件,请勿回复<br>请保管好您的邮箱,避免账号被他人盗用</p><p>知道网络科技团队</p></div></div></td></tr></tbody></table></body>`
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if(error) {
            return console.log(error);
        }
        console.log('mail sent:', info.response);
    });
};

三、单独写redis模块,暴露出去

const redis = require('redis');
const config = {
    url: '服务器的IP',
    port: 6379,
    password: '设置的Redis密码'
}

const client = redis.createClient(config.port, config.url); // 实例redis对象

//连接错误处理
client.on("error", err => {
    console.log('redis connect err', err);
});

client.on('connect', () => {
    console.log('redis connect success');
})

//验证redis
client.auth(config.password);

const redisHelper = {};

/**
 * redisHelper setString function
 * @param key
 * @param value
 * @param expire
 */
redisHelper.setString = (key, value, expire) => {
    return new Promise((resolve, reject) => {
        client.set(key, value, function (err, result) {
            if (err) {
                console.log(err);
                reject(err);
            }

            if (!isNaN(expire) && expire > 0) {
                client.expire(key, parseInt(expire));
            }
            resolve(result)
        })
    })
}

/**
 * redisHelper getString function
 * @param key
 */
redisHelper.getString = (key) => {
    return new Promise((resolve, reject) => {
        client.get(key, function (err, result) {
            if (err) {
                console.log(err);
                reject(err)
            }
            resolve(result)
        });
    })
}

module.exports = redisHelper;

四、服务器配置redis(环境是Ubuntu)

  • 1、执行安装命令,安装成功则会直接启动
sudo  apt-get install redis-server
  • 2、查看redis服务的状态
ps -aux|grep redis
  • 3、配置redis服务
    找到/et/redis/redis.conf文件修改如下 ,注释掉 127.0.0.1 #bind 127.0.0.1,如果不需要远程连接redis则不需要这个操作,下面两个分别是开启远程连接和修改Redis密码
    image.png
    image.png
  • 4、测试密码是否设置成功,输入命令,出现ok就代表成功
redis-cli
auth '密码'
  • 5、如果是阿里云服务器,记得在安全组添加端口号,redis默认的是6379

五、实现发送邮箱接口

async email(ctx) {
        ctx.verifyParams({
            email: {type: 'string', required: true},
            username: {type: 'string', required: true},
            password: {type: 'string', required: true}
        })
        const user = ctx.request.body
        const code = parseInt(Math.random(0, 1) * 10000) //生成随机验证码
        const judgeEmail = await User.findOne({email: user.email})
        if (judgeEmail) {
            ctx.fail('该邮箱已经注册')
        } else {
            const key= user.email
            const result = await redisHelper.setString(newCode, code, 60 * 5)
            if(result === 'OK'){
                nodemailer(user, code)
                ctx.success('', '已发送')
            }
        }
    }

六、实现注册接口

async create(ctx) {
        ctx.verifyParams({
            username: {type: 'string', required: true},
            password: {type: 'string', required: true},
            code: {type: 'string', required: true},
            email: {type: 'string', required: true}
        })
        const {username, code, password, email} = ctx.request.body
        const repeatedUser = await User.findOne({username})
        if (repeatedUser) {
            ctx.fail('账户名已经存在')
        } else {
           const result = await redisHelper.getString(email)
            if(result === code){
                await User(ctx.request.body).save()
                ctx.success('', '注册成功')
            }else{
                ctx.fail('请输入正确验证码')
            }
        }
    }

相关文章

  • Nodejs+koa+redis+nodemailer 实现发送

    一、首先安装依赖 二、单独写nodemailer模块,暴露出去 三、单独写redis模块,暴露出去 四、服务器配置...

  • RocketMQ架构设计之发送消息的实现

    RocketMQ 发送普通消息有三种实现方式:可靠同步发送、可靠异步发送、单向(Oneway)发送。 同步:发送者...

  • 菜鸟Python(3)

    使用类-发送消息 实现结果:通过 twilio 实现给手机发送短信 下载 twilio 进入 cmd 命令窗口,选...

  • 第二十八章 使用 Plumbum 和 yagmail 打造一个发

    一、思路 需求: 实现在命令行里调用 Python 脚本实现发送邮件,通过给脚本传入不同的参数,实现给不同的人发送...

  • SKPSMTPMessage

    SKPSMTPMessage 可以自己实现邮件发送,采用系统的邮件发送会弹出邮件发送框,如果要求静默发送邮件可参照...

  • java发送邮件(附件可选)

    java实现发送邮件,可以带附件发送。。。。。。 pom.xml: java代码:

  • 关于自定义聊天功能(理论篇)

    先上效果图 实现的功能, 发送文字,发送系统的emoji,发送图片,发送语音,消息的重发。 控件封装思路 整体采用...

  • SpringBoot gradle 中使用RabbitMQ(二)

    发送端服务器 注册队列 -- 配置文件实现 消息发送 接收端服务器 实现方式一 实现方式二: 测试类 测试过程 启...

  • runtime的消息机制

    任何方法调用本质:发送一个消息,用runtime发送消息,OC底层实现通过runtime实现; 我们平时书写的代码...

  • runtime介绍

    前言:任何方法调用的本质:发送一个消息,用runtime来发送消息,OC底层实现通过runtime来实现。 run...

网友评论

      本文标题:Nodejs+koa+redis+nodemailer 实现发送

      本文链接:https://www.haomeiwen.com/subject/yfwlyktx.html