ECS-CMD/YuNan-system-start/src/main/java/com/yunan/service/impl/EmailServiceImpl.java

52 lines
1.7 KiB
Java
Raw Normal View History

2024-11-09 13:41:10 +08:00
package com.yunan.service.impl;
2024-11-09 16:49:13 +08:00
import com.yunan.constant.ResponseCode;
import com.yunan.response.ApiResponse;
2024-11-09 13:41:10 +08:00
import com.yunan.service.EmailService;
2024-11-09 16:49:13 +08:00
import com.yunan.util.RedisUtils;
import com.yunan.util.VerificationCodeUtils;
2024-11-09 13:41:10 +08:00
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
2024-11-09 16:49:13 +08:00
import java.util.concurrent.TimeUnit;
2024-11-09 13:41:10 +08:00
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
2024-11-09 16:49:13 +08:00
@Autowired
RedisUtils redisUtils;
public ApiResponse<String> sendMail(String email) throws MessagingException {
// 生成验证码
String code = VerificationCodeUtils.generateCode(6);
// 发送邮件
String subject = "注册验证码";
String content = "尊敬的用户,您的验证码为:" + code + ",有效期5分钟,请勿泄漏!";
2024-11-09 13:41:10 +08:00
// 创建邮件消息
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
2024-11-09 16:49:13 +08:00
helper.setTo(email);
2024-11-09 13:41:10 +08:00
helper.setSubject(subject);
helper.setText(content, true);
// 发送邮件
mailSender.send(message);
2024-11-09 16:49:13 +08:00
2024-11-10 21:09:44 +08:00
redisUtils.hPutWithExpire("rightCode", email, code, 5, TimeUnit.MINUTES);
2024-11-09 16:49:13 +08:00
return new ApiResponse<>(ResponseCode.SUCCESS, "验证码已发送");
2024-11-09 13:41:10 +08:00
}
}