邮件服务实现类

master
Eterlaze 8 months ago
parent 90ef2d9d95
commit 1213876381

@ -0,0 +1,79 @@
package com.example.api.service.impl;
import com.example.api.model.entity.Code; // 导入Code实体类代表验证码信息
import com.example.api.repository.CodeRepository; // 导入CodeRepository接口用于访问验证码数据
import com.example.api.service.EmailService; // 导入EmailService接口定义邮件服务
import com.example.api.utils.RandomUtil; // 导入RandomUtil工具类用于生成随机数虽然在代码中未使用
import org.springframework.beans.factory.annotation.Autowired; // 导入Autowired注解用于自动注入Bean
import org.springframework.beans.factory.annotation.Value; // 导入Value注解用于注入配置文件中的值
import org.springframework.mail.MailException; // 导入MailException异常类处理邮件发送异常
import org.springframework.mail.SimpleMailMessage; // 导入SimpleMailMessage类构建简单的邮件消息
import org.springframework.mail.javamail.JavaMailSender; // 导入JavaMailSender接口用于发送邮件
import org.springframework.stereotype.Service; // 导入Service注解标识服务组件
import javax.annotation.Resource; // 注解用于注入Spring管理的Bean
/**
*
*/
@Service
public class EmailServiceImpl implements EmailService {
@Resource
private CodeRepository codeRepository; // 注入Code仓库用于数据库操作
@Autowired
private JavaMailSender mailSender; // 自动注入JavaMailSender用于发送邮件
@Value("${spring.mail.username}") // 注入配置文件中定义的邮件发送者地址
private String from; // 邮件发送者地址
/**
*
* @param email
* @return truefalse
* @throws MailException
*/
@Override
public boolean sendVerificationCode(String email) throws MailException {
SimpleMailMessage message = new SimpleMailMessage(); // 创建SimpleMailMessage对象
message.setFrom(from); // 设置邮件发送者
message.setTo(email); // 设置邮件收件人
// 设置邮件标题
message.setSubject("验证码");
// 设置邮件内容,这里硬编码了验证码值,实际应用中应该使用随机生成的验证码
String value = "123456";
message.setText("你的验证码为: " + value + " 十五分钟内有效");
try {
// 发送邮件
// mailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
return false; // 发送失败返回false
}
// 保存验证码到数据库
// 同一主键的email为update操作
codeRepository.save(new Code(email, value));
System.out.println("执行save code");
return true; // 发送成功返回true
}
/**
*
* @param email
* @param value
* @return truefalse
*/
@Override
public boolean checkVerificationCode(String email, String value) {
Code code = codeRepository.findByEmailAndValue(email, value);
// 如果验证码存在且未过期
if (code != null && code.getExp() > System.currentTimeMillis()) {
// 登录成功删除验证码
codeRepository.delete(code);
return true; // 校验成功返回true
}
return false; // 校验失败返回false
}
}
Loading…
Cancel
Save