1.引入maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.72</version>
</dependency>
2.编写接口
@RestController
public class SendController {
@Autowired
private Email sendEmail;
@Autowired
private Create create;
@Autowired
private RedisUtil redisUtil;
Logger logger = LoggerFactory.getLogger(SendController.class);
@RequestMapping(value = "sendEmail", method = RequestMethod.POST)
public Map sendEmailTo(@RequestBody Map map) {
String address = map.get("email").toString();
String code = create.createNumber(4);
if (redisUtil.exists(address + "_Escort_Tool")) {
redisUtil.delete(address + "_Escort_Tool");
}
boolean flag1 = redisUtil.set(address + "_Escort_Tool", code);
boolean flag2 = sendEmail.snedEmail(address, "验证码验证", "验证码:" + String.valueOf(code));
Map m = new HashMap();
if (flag1 && flag2) {
logger.warn("账号:" + address + ",发送邮件成功,验证码为:" + code);
m.put("code", 200);
m.put("msg", "发送成功");
m.put("success", true);
} else {
logger.error("账号:" + address + ",发送邮件失败");
m.put("code", 201);
m.put("msg", "发送失败");
m.put("success", false);
}
return m;
}
@RequestMapping(value = "validateCode", method = RequestMethod.POST)
public Map validateCode(@RequestBody Map map) {
String address = map.get("email").toString();
String code = map.get("code").toString();
Map m = new HashMap();
if (redisUtil.exists(address + "_Escort_Tool")) {
String s = redisUtil.get(address + "_Escort_Tool");
if (code.equalsIgnoreCase(s)) {
logger.warn("账号:" + address + ",验证码验证成功");
m.put("code", 200);
m.put("msg", "验证成功");
m.put("success", true);
} else {
logger.error("账号:" + address + ",验证时验证码失败");
m.put("code", 201);
m.put("msg", "验证失败");
m.put("success", false);
}
} else {
logger.error("账号:" + address + ",验证时验证码失效");
m.put("code", 201);
m.put("msg", "验证码已失效");
m.put("success", false);
}
return m;
}
}
3.编写服务层代码
@Resource
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
@Override
public boolean snedEmail(String to, String subject, String content) {
new Thread(() -> {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}).start();
return true;
}
4.redis工具栏
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
public boolean set(final String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value, 5, TimeUnit.MINUTES);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public boolean exists(final String key) {
if (key.equalsIgnoreCase("null")) {
return false;
}
if (redisTemplate.hasKey(key)) {
return true;
}
return false;
}
public String get(final String key) {
if (exists(key)) {
return (String) redisTemplate.opsForValue().get(key);
}
return null;
}
public List<Object> getList(final String key) {
redisTemplate.setValueSerializer(new StringRedisSerializer());
return redisTemplate.opsForList().range(key, 0, -1);
}
public boolean setList(final String key, List<Object> list) {
try {
redisTemplate.opsForList().leftPushAll(key, list);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public boolean delete(final String key) {
if (redisTemplate.hasKey(key)) {
if (redisTemplate.delete(key)) {
return true;
}
}
return false;
}
}
5.产生随机字符串工具类
@Component
public class Create {
public String createNumber(int length) {
String str = "0123456789";
Random random = new Random();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(9);
stringBuffer.append(str.charAt(number));
}
return String.valueOf(stringBuffer);
}
public String createString(int length) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(52);
stringBuffer.append(str.charAt(number));
}
return String.valueOf(stringBuffer);
}
public String createStringWithNumber(int length) {
String val = "";
Random random = new Random();
for (int i = 0; i < length; i++) {
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
if ("char".equalsIgnoreCase(charOrNum)) {
int tmp = random.nextInt(2) % 2 == 0 ? 64 : 97;
val += (char) (random.nextInt(26) + tmp);
} else if ("num".equalsIgnoreCase(charOrNum)) {
val += String.valueOf(random.nextInt(10));
}
}
return val;
}
}
6.redis配置
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
7.配置跨域请求
@Configuration
public class CrossConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
8.SpringBoot配置(yaml)
spring:
application:
name: SendEmailCodeTool
mail:
default-encoding: utf-8
host: smtp.qq.com
protocol: smtp
username: 发送邮件用户名(你配置用来发送邮件地址,---@qq.com)
password: 邮箱授权码
properties:
mail:
auth: true
starttls:
enable: true
required: true
redis:
host: 127.0.0.1
port: 6379
password: redis密码
jedis:
pool:
max-active: 10
max-wait: -1
min-idle: 0
max-idle: 8
timeout: 5000
server:
port: 8083
servlet:
context-path: /sendEmail
logging:
file:
name: sendEmailCodeLog.log
max-size: 10MB
path: ./log/
pattern:
dateformat: yyyy-MM-dd HH:MM:ss.sss
|