SpringBoot邮箱验证码功能实现和拓展

20231107-可用

1. 首先引入依赖:

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>

2. 编写邮箱配置:

application.yml

我这里以qq邮箱为例,不同的邮箱部分不同,qq邮箱到设置->账号->账号安全->POP3/IMAP/SMTP…服务,开启服务后获取授权码等等信息

spring:
    mail:
      host: smtp.qq.com
      username: liaoyueyue.email@qq.com
      password: 这里填你的授权码
      default-encoding: utf-8

3. 创建邮箱服务发送邮件:

创建一个服务类,该类将负责发送电子邮件。这个服务类应该使用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);
    }
}

4. 其他

上面只是完成了基本需求,你可以根据自身项目需求加强。

创建邮箱工具类:

来判断邮箱格式和生成随机验证码

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);
    }
}
扩展EmailService

验证码存入 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

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");
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
怎么实现? 可以通过利用Spring Boot中的Java MailSender和Random类来实现发送邮箱验证码功能。首先,需要在Spring Boot的配置文件中配置SMTP服务器的相关信息,然后在代码中实现生成随机验证码并发送邮件的逻辑。可以参考下面的代码实现: @Configuration public class MailConfiguration { // 邮件发送方 @Value("${spring.mail.username}") private String from; // SMTP服务器地址 @Value("${spring.mail.host}") private String host; // SMTP服务器端口号 @Value("${spring.mail.port}") private int port; // 邮箱账户名 @Value("${spring.mail.username}") private String username; // 邮箱账户密码 @Value("${spring.mail.password}") private String password; // 是否开启SSL @Value("${spring.mail.properties.mail.smtp.ssl.enable}") private boolean sslEnabled; // 是否开启TLS @Value("${spring.mail.properties.mail.smtp.starttls.enable}") private boolean tlsEnabled; @Bean public JavaMailSender getJavaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(host); mailSender.setPort(port); mailSender.setUsername(username); mailSender.setPassword(password); Properties props = mailSender.getJavaMailProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", tlsEnabled); props.put("mail.smtp.ssl.enable", sslEnabled); return mailSender; } } @Service public class MailService { @Autowired private JavaMailSender javaMailSender; // 生成验证码 public String generateVerificationCode() { Random random = new Random(); int code = random.nextInt(899999) + 100000; return String.valueOf(code); } // 发送邮件 public void sendMail(String to, String subject, String content) throws MessagingException { MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content); javaMailSender.send(message); } } 在上面的代码中,先在配置文件中设置了SMTP服务器的相关信息。然后,在MailService类中,实现了生成随机验证码和发送邮件的方法。generateVerificationCode方法使用Java的Random类来生成六位数的验证码,sendMail方法则使用JavaMailSender发送邮件。发送邮件时,需要创建一个MimeMessage实例,并设置相关的属性(邮件发送方、接收方、主题和内容等)。最后,调用JavaMailSender的send方法发送邮件即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值