此为个人备忘笔记,详细教程还请自行再百度一下
1、pom.xml
<!--发送电子邮件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、application.yml
server:
port: 7000
spring:
profiles:
active: dev
application:
name: xxxxx
#spring:
redis:
host: 127.0.0.1
port: 6379
database: 0
password: #默认为空
timeout: 3000ms #最大等待时间,超时则抛出异常,否则请求一直等待
# 发送邮件 MailProperties
mail:
host: smtp.qq.com
port: 465
username: xxxxxx@qq.com
password: xxxxxxxxxxxxx
protocol: smtps
default-encoding: utf-8
3、控制器发送邮件
package com.jili20.controller;
import com.xxxxxx.client.SystemClient;
import com.xxxxxx.exception.Assert;
import com.xxxxxx.result.ResponseEnum;
import com.xxxxxx.result.Result;
import com.xxxxxx.util.RandomUtils;
import com.xxxxxx.util.RedisCache;
import com.xxxxxx.util.RegexValidateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
/**
* @create 2022/1/15-15:43
*/
@Slf4j
@Api(tags = "发送邮箱")
@RestController
@RequestMapping("/api")
public class ApiEmailController {
@Resource
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String account;
@Resource
private SystemClient systemClient;
@Resource
private RedisCache redisCache;
/**
* 测试 - 发送简单邮件
*/
@ApiOperation("测试 - 发送简单邮件")
@PostMapping("/sendSimpleMail")
public String sendSimpleMail(
@ApiParam("收件地址") @RequestParam String address,
@ApiParam("标题") @RequestParam String subject,
@ApiParam("正文") @RequestParam String body) {
SimpleMailMessage smm = new SimpleMailMessage();
smm.setFrom(account);
smm.setTo(address);
smm.setSubject(subject);
smm.setText(body);
javaMailSender.send(smm);
return "发送成功";
}
@ApiOperation("用户 - 修改密码 - 发送邮箱验证码")
@GetMapping("/sendMailCode/{email}")
public Result send(
@ApiParam(value = "邮箱地址", required = true)
@PathVariable String email, HttpServletRequest request) throws Exception {
// 邮箱地址不能为空
Assert.notEmpty(email, ResponseEnum.EMAIL_NULL_ERROR);
// 邮箱地址不正确
Assert.isTrue(RegexValidateUtils.checkEmailAddressOk(email), ResponseEnum.EMAIL_ADDRESS_ERROR);
// 1、防止暴力不断发送 ======================>
// 同一个邮箱,1分钟发送1次验证码;同一个 IP,1小时内最多发送5次验证码
String remoteAddr = request.getRemoteAddr();
// 将IP地址的:号替换成_
if (remoteAddr != null) {
remoteAddr = remoteAddr.replaceAll(":", "_");
}
// 取出来,如果没有,通过
Integer ipSendTimeValue = redisCache.getCacheObject("key_email_send_ip:" + remoteAddr);
Integer ipSendTime;
if (ipSendTimeValue != null) {
ipSendTime = ipSendTimeValue;
} else {
ipSendTime = 1;
}
// 限制发送 5 次(测试发现从 0 次开始算)
Integer time = 4;
if (ipSendTime > time) {
return Result.fail().message("请不要频繁发送验证码");
}
// 检查 redis 中有没有电话号
Object hasPhoneSend = redisCache.getCacheObject("key_email_send_address:" + email);
if (hasPhoneSend != null) {
return Result.fail().message("请不要频繁发送验证码");
}
// /======================>
// 调用远程方法-判断邮箱地址是否已经注册(未被注册才发送邮件验证码)
boolean result = systemClient.checkEmail(email);
log.info("result = " + result);
// 系统不存在此邮箱
Assert.isTrue(result == true, ResponseEnum.EMAIL_NO_EXIST_ERROR);
// 生成4位随机数字
String code = RandomUtils.getFourBitRandom();
// 发送邮件
SimpleMailMessage smm = new SimpleMailMessage();
String subject = "验证码";
// xxxxxxxx@qq.com 您正在修改邮箱,本次操作的验证码为 1234 , 有效时间 10 分钟,请您及时进行操作!
String body = "您好 " + email + " !\n\n您的验证码是: " + code + " ,10 分钟内有效,请匆泄漏。如非本人操作,请忽略此邮件。" ;
// 自定义发件人名
smm.setFrom(new InternetAddress(MimeUtility.encodeText("自定义发件人名")+"<xxxxxx@qq.com>").toString());
smm.setTo(email);
smm.setSubject(subject);
smm.setText(body);
javaMailSender.send(smm);
// 2、做记录: ======================>
// 发送 code 次数
if (ipSendTime == null) {
ipSendTime = 0;
}
ipSendTime++;
// 设置 IP key 有效时长为1个小时
redisCache.setCacheObject("key_email_send_ip:" + remoteAddr, ipSendTime, 60, TimeUnit.MINUTES);
// 设置 邮箱 key,间隔要超过 1 分钟发送一次(true 为占位字符串)
redisCache.setCacheObject("key_email_send_address:" + email, true, 1, TimeUnit.MINUTES);
// /======================>
// 将验证码存入 redis, 10分钟内有效
redisCache.setCacheObject("key_mail_send_code:" + email, code, 10, TimeUnit.MINUTES);
return Result.ok("发送邮件成功");
}
}