赞
踩
20231107-可用
pom.xml
第二个依赖可以使用Apache Commons Lang库中的RandomStringUtils
来生成随机验证码。创建一个工具类来生成验证码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
application.yml
我这里以qq邮箱为例,不同的邮箱部分不同,qq邮箱到设置->账号->账号安全->POP3/IMAP/SMTP…服务,开启服务后获取授权码等等信息
spring:
mail:
host: smtp.qq.com
username: liaoyueyue.email@qq.com
password: 这里填你的授权码
default-encoding: utf-8
创建一个服务类,该类将负责发送电子邮件。这个服务类应该使用Spring的JavaMailSender
来发送电子邮件。
EmailService
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender mailSender; public void sendVerificationCode(String toEmail, String code) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("liaoyueyue.email@qq.com"); message.setTo(toEmail); message.setSubject("邮件的主题,自己设置"); message.setText("您的验证码为: " + code); mailSender.send(message); } }
遇到 "Could not autowire. No beans of 'JavaMailSender' type found..."
错误,这通常意味着Spring Boot没有找到JavaMailSender的bean定义。检查第二步的编写邮箱配置,实在不行采用Bean,参考下面代码。
EmailConfig
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; @Configuration public class EmailConfig { @Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("your-smtp-server.com"); mailSender.setUsername("your-email@example.com"); mailSender.setPassword("your-email-password"); mailSender.setDefaultEncoding("utf-8"); return mailSender; } }
后续创建一个EmailController来进行测试邮箱是否能发送:
EmailController
下面代码的EmailService
根据自己路径导包
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; @RestController @RequestMapping("/email") public class EmailController { @Autowired EmailService emailService; @PostMapping("/send-verification-code") public void sendVerificationCode(String email) { String code = RandomStringUtils.randomAlphanumeric(6); // 生成6位验证码 emailService.sendVerificationCode(email, code); } }
上面只是完成了基本需求,你可以根据自身项目需求加强。
来判断邮箱格式和生成随机验证码
EmailUtils
import org.apache.commons.lang3.RandomStringUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created with IntelliJ IDEA. * Description: 邮箱工具类 * User: liaoyueyue * Date: 2023-11-06 * Time: 1:05 */ public class EmailUtils { private static final String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@(.+)$"; /** * 判断邮箱格式是否合法 * @param email 用户邮箱 * @return 是否为合法邮箱 */ public static boolean isEmailValid(String email) { Pattern pattern = Pattern.compile(EMAIL_REGEX); Matcher matcher = pattern.matcher(email); return matcher.matches(); } /** * 根据 length 来生成随机验证码 * 使用Apache Commons Lang库中的`RandomStringUtils`来生成随机验证码。创建一个工具类来生成验证码 * @param length 验证码长度 * @return 指定长度验证码 */ public static String generateVerificationCode(int length) { return RandomStringUtils.randomAlphanumeric(length); } }
验证码存入 redis ,给验证码上5分钟时间过期等等
EmailService
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; /** * Created with IntelliJ IDEA. * Description: * User: liaoyueyue * Date: 2023-11-06 * Time: 0:21 */ @Service public class EmailService { @Autowired JavaMailSender mailSender; @Autowired RedisTemplate redisTemplate; /** * 发送验证码到邮箱 * @param toEmail 用户的邮箱 * @param code 验证码 */ public void sendVerificationCode(String toEmail, String code) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("liaoyueyue.email@qq.com"); message.setTo(toEmail); message.setSubject("个人博客系统"); message.setText("您的验证码为: " + code); mailSender.send(message); } /** * 生成和存储验证码到 redis * @param email 邮箱 * @return 邮箱验证码 */ public String generateAndStoreVerificationCode(String email) { String key = "verification_code:" + email; String code = EmailUtils.generateVerificationCode(6); redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES); // 设置验证码的过期时间为5分钟 return code; } /** * 从 redis 中拿 验证码 * @param email 邮箱 * @return 邮箱验证码 */ public String getVerificationCode(String email) { String key = "verification_code:" + email; return (String) redisTemplate.opsForValue().get(key); } /** * 检查验证码是否还有效 * @param email 邮箱 * @param code 验证码 * @return */ public boolean isVerificationCodeValid(String email, String code) { // 拿 redis 中的验证码 String storedCode = getVerificationCode(email); return code != null && code.equals(storedCode); } /** * 删除Redis中的验证码,用户登录后可以先检验是否有效后进行删除 * @param email 邮箱 */ public void deleteVerificationCode(String email) { String key = "verification_code:" + email; redisTemplate.delete(key); } }
EmailController
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Created with IntelliJ IDEA. * Description: * User: liaoyueyue * Date: 2023-11-06 * Time: 23:47 */ @Controller @ResponseBody @Slf4j @RequestMapping("/email") public class EmailController { @Autowired EmailService emailService; @Autowired UserService userService; @PostMapping("/sendverificationcode") public AjaxResult sendVerificationCode(String email) { // 1.非空验证 if (!StringUtils.hasLength(email)) { return AjaxResult.fail(-1, "illegal request"); } // 2.邮箱校验 // 邮箱格式判断 if (!EmailUtils.isEmailValid(email)) { return AjaxResult.fail(-1, "Email is illegal"); } // 邮箱是否存在 int emailExist = userService.queryEmailExist(email); if (emailExist > 0) { return AjaxResult.fail(-1, "Email already exists"); } // 3.发送6位验证码到用户邮箱 try { String verificationCode = emailService.generateAndStoreVerificationCode(email); emailService.sendVerificationCode(email, verificationCode); } catch (Exception e) { e.printStackTrace(); log.error("发送验证码邮件时发生异常了!", e); } return AjaxResult.success(200, "Successfully sent"); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。