52 lines
1.7 KiB
Java
52 lines
1.7 KiB
Java
package com.yunan.service.impl;
|
|
|
|
import com.yunan.constant.ResponseCode;
|
|
import com.yunan.response.ApiResponse;
|
|
import com.yunan.service.EmailService;
|
|
import com.yunan.util.RedisUtils;
|
|
import com.yunan.util.VerificationCodeUtils;
|
|
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;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
@Service
|
|
public class EmailServiceImpl implements EmailService {
|
|
@Autowired
|
|
private JavaMailSender mailSender;
|
|
|
|
@Value("${spring.mail.username}")
|
|
private String from;
|
|
@Autowired
|
|
RedisUtils redisUtils;
|
|
|
|
|
|
public ApiResponse<String> sendMail(String email) throws MessagingException {
|
|
|
|
// 生成验证码
|
|
String code = VerificationCodeUtils.generateCode(6);
|
|
|
|
// 发送邮件
|
|
String subject = "注册验证码";
|
|
String content = "尊敬的用户,您的验证码为:" + code + ",有效期5分钟,请勿泄漏!";
|
|
|
|
// 创建邮件消息
|
|
MimeMessage message = mailSender.createMimeMessage();
|
|
MimeMessageHelper helper = new MimeMessageHelper(message, true);
|
|
helper.setFrom(from);
|
|
helper.setTo(email);
|
|
helper.setSubject(subject);
|
|
helper.setText(content, true);
|
|
|
|
// 发送邮件
|
|
mailSender.send(message);
|
|
|
|
redisUtils.hPutWithExpire("rightCode", email, code, 5, TimeUnit.MINUTES);
|
|
return new ApiResponse<>(ResponseCode.SUCCESS, "验证码已发送");
|
|
}
|
|
} |