springboot整合redis實現發送郵箱並驗證

1.起步

pom文件

  <!--集成redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.4.1.RELEASE</version>
        </dependency>
        <!--郵箱-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

下面是yml配置

#設置端口號
server:
  port: 8080
#配置數據源
spring:
  mail:
    #QQ郵箱這不用改
    host: smtp.qq.com
    #你的郵箱
    username: [email protected]
    #你的授權碼
    password: XXXXXX
    default-encoding: UTF-8
  redis:
    #redis服務器地址
    host: XXXXXX
    #Redis服務器連接端口
    port: 6379
    #Redis服務器連接密碼(默認為空)
    password: XXX
    jedis:
      pool:
        #連接池最大阻塞等待時間(使用負值表示沒有限制)
        max-wait: 1000
        #連接池最大連接數(使用負值表示沒有限制)
        max-active: 100
        #連接池中的最大空閑連接
        max-idle: 20
        #連接池中的最小空閑連接
        min-idle: 0
        #連接超時時間(毫秒)
    timeout: 30000
郵箱授權碼不知道的話QQ郵箱開通一下

在這裡插入圖片描述

2.工具類

郵箱工具類

package com.example.demo.util;

/**
 * @Classname MailServiceUtils
 * @Description TODO
 * @Author 86176
 * @Date 2021-12-17 15:04
 * @Version 1.0
 **/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class MailServiceUtils{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private JavaMailSender mailSender;
    /**
     * @param from 發送人
     * @param to 接收人
     * @param subject 主題
     * @param content 內容
     */
    public void sendMail(String from,String to, String subject, String content){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message); logger.info("郵件成功發送!");
        } catch (MailException e) {
            logger.error("發送郵件錯誤:",e);
        }
    }
}

redis亂碼解決

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Classname Redisconfig
 * @Description TODO
 * @Author 86176
 * @Date 2021-12-06 10:02
 * @Version 1.0
 **/
@Configuration
public class Redisconfig {


    @Bean(name="redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(redisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(redisSerializer);
        //key haspmap序列化
        template.setHashKeySerializer(redisSerializer);
        //
        return template;
    }
}

3.controller搭建

按要求更改

package com.example.demo.controller;

import com.example.demo.util.MailServiceUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @Classname EmailController
 * @Description TODO  郵箱發送
 * @Author 86176
 * @Date 2021-12-17 15:28
 * @Version 1.0
 **/
@Controller
public class EmailController {

    @Resource
    private MailServiceUtils mailServiceUtils;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 發送驗證碼 redis存儲驗證碼
     * @param to 被發送的郵箱賬號
     * @return
     */
    @PostMapping("/fasong")
    @ResponseBody
    public String email(String to) {
        try {
            //生成6位隨機數
            String i = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
            //發送郵箱
            mailServiceUtils.sendMail("[email protected]", to, "驗證碼", i);
            //redis保存驗證碼
            redisTemplate.opsForValue().set(to, i);
        } catch (Exception e) {
            return "報錯";
        }
        return "OK";
    }

    /**
     * 郵箱驗證
     * @param to 被發送的郵箱賬號
     * @param yzm 輸入的驗證碼判斷
     * @return
     */
    @PostMapping("/yz")
    @ResponseBody
    public String yz(String to, String yzm) {
        //根據郵箱帳號取出驗證碼
        String o = (String) redisTemplate.opsForValue().get(to);
        if (o.equals(yzm)){
            return "OK";
        }
        return "No";
    }

    @RequestMapping("/abc")
    public String abc() {
        return "QQemail";
    }
}

4.前端搭建

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
     <div>
         接收方郵箱號 <input type="text" id="to">
         <input type="button" value="發送驗證碼" id="yzm">
         驗證碼<input type="text" id="yz">
         <input type="submit" value="驗證" id="y">
     </div>
<script type="text/javascript"  src="../static/jquery-1.8.3.js"></script>
<script>
    /**
     * 發送驗證碼
     */
    $("#yzm").click(function() {
        $.ajax({
            url : "/fasong",
            type : "post",
            data : {
                "to":$("#to").val()
            },
            success : function(data) {
                alert(data)
            }
        })
    })
    /**
     * 驗證碼判斷
     */
    $("#y").click(function() {
        $.ajax({
            url: "/yz",
            type: "post",
            data: {
                "to": $("#to").val(),
                "yzm": $("#yz").val()
            },
            success: function (data) {
                alert(data)
            }
        })
    })
</script>
</body>
</html>

結果

redis和郵箱

頁面

總結

到此這篇關於springboot整合redis實現發送郵箱並驗證的文章就介紹到這瞭,更多相關springboot redis發送郵箱內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: