SpringBoot 轻松实现发送邮箱验证码+Redis缓存(附带HTML模板)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
@Autowired
private StringRedisTemplate redisTemplate;
public void sendEmail(String to, String subject, String templateName, Context context) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setTo(to);
helper.setSubject(subject);
String htmlContent = templateEngine.process(templateName, context);
helper.setText(htmlContent, true);
mailSender.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendEmailWithCode(String to, String code) {
Context context = new Context();
context.setVariable("code", code);
sendEmail(to, "Your Verification Code", "email/emailTemplate", context);
}
public void saveCodeToRedis(String key, String code, long timeout, TimeUnit unit) {
ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
opsForValue.set(key, code, timeout, unit);
}
public String getCodeFromRedis(String key) {
ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
return opsForValue.get(key);
}
}
这段代码示例展示了如何在SpringBoot应用中使用JavaMailSender
发送邮件,TemplateEngine
处理HTML模板,以及StringRedisTemplate
进行缓存操作。sendEmailWithCode
方法接收接收者邮箱地址和验证码,并使用Thymeleaf模板引擎发送带有验证码的邮件。同时,提供了saveCodeToRedis
和getCodeFromRedis
方法来操作Redis缓存。
评论已关闭