SpringBoot实现发送自定义验证码

45 篇文章 9 订阅
42 篇文章 1 订阅

前言

随着互联网的不断发展,验证码的作用越来越重要。作为常见的一种防范机制,验证码能有效避免机器人或者别有用心的人利用自动化程序进行注入攻击、暴力破解等恶意行为。在本文中,我们将讲解如何使用SpringBoot框架实现自定义验证码发送功能。您可根据自己应用场景的不同,对代码进行调整扩展。

环境和工具

  • IDE:IntelliJ IDEA
  • JDK:1.8
  • SpringBoot版本:2.4.5.RELEASE
  • Maven

实现思路

我们要实现的自定义验证码发送功能,其实就是在用户完成表单填写后,向用户发送一条验证码信息,以确定用户身份是否合法。在SpringBoot中,我们最好的方式就是借助Spring Framework自带的邮件发送工具实现。具体实现步骤如下:

  1. 定义邮箱模板和验证码生成方法
  2. 定义邮件发送服务
  3. 在控制层调用发送服务,并返回相应的结果信息

接下来,我们将逐步讲解具体步骤。

正文

1. 定义邮箱模板和验证码生成方法

在这里,我们先定义一个验证码生成工具类,通过调用Java自带的Random和StringBuilder类生成一个长度为6的纯数字验证码:

import java.util.Random;

/**
 * 验证码生成工具类
 */
public class CodeUtil {

    /**
     * 生成随机验证码
     *
     * @return 验证码
     */
    public static String generateCode() {
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int num = random.nextInt(10);
            code.append(num);
        }
        return code.toString();
    }
}

接下来,我们需要定义发送邮件的模板,在这里我使用了Thymeleaf模板引擎,处理HTML模板:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
    <h1>验证码</h1>
    <p th:text="'您的验证码是:' + ${captcha}" style="font-size: 20px;color: #3385ff;"></p>
</body>
</html>

2. 定义邮件发送服务

在这里,我们定义一个基于JavaMailSender的邮件发送服务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
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.io.File;
import java.io.UnsupportedEncodingException;

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送邮件
     *
     * @param to         收件人邮箱地址
     * @param code       验证码
     * @param subject    邮件主题
     * @param template   邮件模板
     * @param attachment 附件地址(可选)
     */
    public void sendEmail(String to, String code, String subject, String template, String attachment)
            throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("您的发件人邮箱地址", "您的昵称");
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(CodeUtil.generateCode(), true);

        // 添加附件
        if (attachment != null) {
            FileSystemResource fileSystemResource = new FileSystemResource(new File(attachment));
            helper.addAttachment("附件", fileSystemResource);
        }

        javaMailSender.send(message);
    }
}

3. 在控制层调用发送服务,并返回相应的结果信息

最后一步,我们在控制层调用发送服务,并返回相应的结果信息。我们定义一个Controller,其中包含一个URL接口用于发送邮件。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;

@RestController
public class EmailController {

    @Autowired
    private EmailService emailService;

    /**
     * 发送邮件
     *
     * @param to 邮件收件人
     * @return 成功或失败提示信息
     */
    @GetMapping("/sendEmail")
    public String sendEmail(@RequestParam String to) {
        try {
            String code = CodeUtil.generateCode();
            String subject = "验证码信息";
            String template = "验证码模板";
            String attachment = null;

            emailService.sendEmail(to, code, subject, template, attachment);
            return "验证码发送成功,请注意查收!";
        } catch (MailException | MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
            return "验证码发送失败,请重试!";
        }
    }
}

最后,我们需要配置邮件发送相关的信息,如邮件服务器地址、端口号、账号密码等信息。在 application.properties 或者 application.yml 中添加如下配置:

spring.mail.host=smtp.163.com #SMTP 服务器地址
spring.mail.username=your_username@163.com #发送者邮箱账号
spring.mail.password=your_password #发送者邮箱密码
spring.mail.port=25 #SMTP服务器端口号
spring.mail.protocol=smtp #邮件协议,默认为smtp
spring.mail.properties.mail.smtp.auth=true #SMTP 登录认证
spring.mail.properties.mail.smtp.starttls.enable=true #如果是使用加密类的邮件协议,需要设置此项为true

总结

本文讲解了如何使用SpringBoot框架实现自定义验证码发送功能。通过验证码的使用,可以有效保障您应用的安全性。希望您在开发过程中能够参考以上内容,实现更加优秀的应用程序。

参考资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot发送邮箱验证码可以通过使用 JavaMailSender 来实现。首先,你需要在 `application.properties` 或 `application.yml` 配置文件中配置邮件服务器的相关信息,如下所示: application.properties: ```properties spring.mail.host=your.mail.server spring.mail.port=your.mail.port spring.mail.username=your.username spring.mail.password=your.password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` application.yml: ```yaml spring: mail: host: your.mail.server port: your.mail.port username: your.username password: your.password properties: mail: smtp: auth: true starttls: enable: true ``` 接下来,你可以创建一个邮件服务类来发送验证邮件,示例如下: ```java 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 javaMailSender; public void sendVerificationCode(String to, String code) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject("验证码"); message.setText("您的验证码是:" + code); javaMailSender.send(message); } } ``` 在上述示例中,`JavaMailSender` 是由 Spring Boot 自动配置的邮件发送器。你可以在需要发送验证码的地方调用 `sendVerificationCode` 方法来发送邮件。 注意:为了使用JavaMailSender,你需要在项目的依赖管理文件(例如 pom.xml)中添加相应的依赖。你可以添加以下依赖来使用 Spring Boot 提供的邮件支持: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 以上就是使用 Spring Boot 发送邮箱验证码的简单示例。你可以根据自己的实际需求进行调整和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沙漠真有鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值