Springboot+JavaMail+redis(jedis作为客户端)实现邮件发送与验证码功能

POM

<!-- springboot -->
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.2.2.RELEASE</version>
	<relativePath/> 
</parent>

<!-- 引入邮件发送功能 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<optional>true</optional>
</dependency>

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.61</version>
</dependency>

properties

# redis setting
spring.redis.host=192.168.124.12
spring.redis.port=6379
spring.redis.password=root
# Redis database index(default 0)
spring.redis.database=0
# Maximum blocking waiting time of connection pool (negative value indicates no limit)
spring.redis.jedis.pool.max-wait=120
# Maximum active connection in connection pool
spring.redis.jedis.pool.max-active=120
# Maximum free connection in connection pool
spring.redis.jedis.pool.max-idle=8
# Minimum free connection in connection pool
spring.redis.jedis.pool.min-idle=0
# connect timeout (millisecond)
spring.redis.timeout=6000
# mailsender
mail.sender=XXX科技有限公司<18xxxxx5@163.com>

yml 需要在163邮箱配置中设置第三方登录的授权

server:
  servlet:
    context-path: /testserver
  port: 88
spring:
  resources:
    static-locations: classpath:static/
  mail:
    host: smtp.163.com
    username: 18xxxxx65@163.com
    password: LTOWEVORZHBRPMJN
    default-encoding: UTF-8
    properties:
      mail:
        smtp:
          timeout: 10000
          connectiontimeout: 10000
          writetimeout: 10000
          socketFactory:
            port: 465
            class: javax.net.ssl.SSLSocketFactory
            fallback: false
          auth: true
          starttls:
            enable: true
            required: true

一个邮箱service类

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Slf4j
@Component
public class MailService {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${mail.sender}")
    private String SENDER;

//发送一个文本页邮件
    public void sendSimpleMail(String subject, String content, String[] cc, String[] bcc, String... to) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(SENDER);
        message.setTo(to);
        message.setCc(cc);
        message.setBcc(bcc);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            log.info("Simple Mail Send Successful");
        } catch (Exception e) {
            log.error("Simple Mail Send failed, the detail is :" + e);
        }
    }

//发送一个网页邮件,可设置丰富样式
    public void sendHtmlMail(String subject, String content, String[] cc, String[] bcc, String... to) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = buildMimeMessageHelper(subject, content, cc, bcc, message, to);
            mailSender.send(message);
            log.info("Html Mail Send Successful");
        } catch (MessagingException e) {
            log.error("Html Mail Send failed, the detail is :", e.getMessage());
        }

    }

//发送带有附件的邮件
    public void sendAttachmentsMail(String subject, String content, String filePath,
                                    String[] cc, String[] bcc, String... to) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = buildMimeMessageHelper(subject, content, cc, bcc, message, to);
            File file = new File(filePath);
            // get file path
            String fileName = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/") + 1);
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            log.info("Attachments Mail Send Successful");
        } catch (MessagingException e) {
            log.error("Attachments Mail Send failed, the detail is :", e.getMessage());
        }
    }

    public void sendInlineResourceMail(String subject, String content, String rscPath,
                                       String rscId, String[] cc, String[] bcc, String... to) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = buildMimeMessageHelper(subject, content, cc, bcc, message, to);
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);
            mailSender.send(message);
            log.info("InlineResource Mail Send Successful");
        } catch (MessagingException e) {
            log.error("InlineResource Mail Send failed, the detail is :", e.getMessage());
        }
    }

    private MimeMessageHelper buildMimeMessageHelper(String subject, String content, String[] cc,
                                                     String[] bcc, MimeMessage message, String... to) throws MessagingException {
        // true means should create a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(SENDER);
        helper.setTo(to);
        helper.setCc(cc);
        helper.setBcc(bcc);
        helper.setSubject(subject);
        helper.setText(content, true);
        return helper;
    }
}

一个jedis工具类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
 
/**
 * @author 徒手千行代码无bug
 */
@Component
public class JedisCacheUtil {
 
	@Autowired
	private JedisPool jedisPool;

	/**
	 * Description:给某个key设值
	 */
	public void set(String key, String value) {
		Jedis client = jedisPool.getResource();
		try {
			client.set(key, value);
		} finally {
			returnJedis(client);
		}
	}

	/**
	 * Description:给某个key设值,设置过期时间expire,-1表示不过期,遵循redis的LRU算法。
	 */
	public void set(String key, String value, int expireSecond) {
		Jedis client = jedisPool.getResource();
		try {
			client.set(key, value);
			if(expireSecond != -1) {
				client.expire(key, expireSecond);
				//另一种设置方式:NX是不存在时才set,XX是存在时才set,EX是秒,PX是毫秒:client.set(key, value, "NX", "EX", expireSecond);
			}
		} finally {
			returnJedis(client);
		}
	}

	/**
	 * Description:根据key获取value
	 */
	public String get(String key) {
		Jedis client = jedisPool.getResource();
		try {
			return client.get(key);
		} finally {
			returnJedis(client);
		}
	}

	/**
	 * Description:判断key是否存在
	 */
	public boolean existKey(String key) {
		Jedis client = jedisPool.getResource();
		try {
			return client.exists(key);
		} finally {
			returnJedis(client);
		}
	}

	/**
	 * Description:根据key删除
	 */
	public void delKey(String key) {
		Jedis client = jedisPool.getResource();
		try {
			client.del(key);
		} finally {
			returnJedis(client);
		}
	}

	/**
	 * Description:关闭jedis
	 */
	public void returnJedis(Jedis jedis) {
		if (jedis != null) {
			jedis.close();
		}
	}
}

controller调用

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author 徒手千行代码无bug
 */
@Api(tags = "公共接口")
@RestController
@RequestMapping()
@CrossOrigin(origins = "*")
public class CommonController
{
    @Autowired
    private MailService sMail;

    @Autowired
    private JedisCacheUtil jedis;

    @Autowired
    private UserManageServiceImpl sUserManage;
    /**
     * @param email
     * @return CommonResult
     */
    @ApiOperation("发送验证码到邮箱")
    @PostMapping("/sendMessageByMail")
    public ResponseEntity<CommonResult> sendMessageByMail(@RequestBody String email)
    {
        CommonResult result = new CommonResult();
        result.setResultCode("0");
        result.setResultMessage("SUCCESS");
        try {
        	// 生成6位随机数字
            String code = StringUtil.generateRandomString(6);
            sMail.sendSimpleMail("Verification Code", code, new String[]{}, new String[]{}, email);
            jedis.set(email, code, 120);
        } catch (Exception e) {
            result.setResultCode("-1");
            result.setResultMessage("send email error, please contact the administrator!");
            return new ResponseEntity<>(result, HttpStatus.OK);
        }
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * @param verificationInfo
     * @return CommonResult
     */
    @ApiOperation("验证验证码")
    @PostMapping("/validateCode")
    public ResponseEntity<CommonResult> validateCode(@RequestBody JSONObject verificationInfo)
    {
        CommonResult result = new CommonResult();
        try {
            String email = verificationInfo.getString("email");
            String code = verificationInfo.getString("code");
            String codeInRedis = jedis.get(email);
            if( !jedis.existKey(email) || codeInRedis == null || !codeInRedis.equals(code))
            {
				result.setResultCode("3");
                result.setResultMessage("verification code is incorrect or invalid, please sent again!");
            }else {
                jedis.delKey(email);
                result.setResultCode("0");
                result.setResultMessage("SUCCESS");
            }
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            result.setResultCode("-1");
            result.setResultMessage("validate code failed, please contact the administrator!");
            return new ResponseEntity<>(result, HttpStatus.OK);
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值