如何使用 springboot 结合邮件发送验证码?

要使用Spring Boot结合邮件发送验证码,可以按照以下步骤:

1,添加相关依赖

pom.xml文件中添加Spring Boot Mail和Apache Commons Lang依赖:

<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.9</version>
</dependency>

2,配置SMTP邮件服务器

application.propertiesapplication.yml文件中添加SMTP邮件服务器配置:

# SMTP服务器地址
spring.mail.host=smtp.example.com
# SMTP服务器端口
spring.mail.port=587
# 是否启用TLS
spring.mail.properties.mail.smtp.starttls.enable=true
# SMTP服务器用户名
spring.mail.username=yourusername
# SMTP服务器密码
spring.mail.password=yourpassword
# 邮件编码
spring.mail.default-encoding=UTF-8

3,创建邮件服务类

创建一个邮件服务类来发送邮件,例如:

import org.apache.commons.lang3.RandomStringUtils;
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 email) {
        String code = RandomStringUtils.randomNumeric(6);
        String subject = "Verification Code";
        String text = "Your verification code is " + code;
        sendEmail(email, subject, text);
    }

    private void sendEmail(String email, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(email);
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
    }

}

此类包含一个sendVerificationCode方法,该方法生成一个6位随机数字验证码并将其发送到指定的电子邮件地址。

4,调用邮件服务类

在需要发送验证码的位置调用邮件服务类的sendVerificationCode方法,例如:

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

@RestController
@RequestMapping("/api")
public class MyController {

    @Autowired
    private EmailService emailService;

    @PostMapping("/verify")
    public String verifyEmail(@RequestParam String email) {
        emailService.sendVerificationCode(email);
        return "Verification code sent to " + email;
    }

}

在此示例中,调用verifyEmail方法将向指定的电子邮件地址发送验证码,并返回一个消息,该消息指示验证码已发送到该地址。

以上就是使用Spring Boot结合邮件发送验证码的基本步骤,根据实际情况可以进行适当修改。

猜你喜欢

转载自blog.csdn.net/m0_72605743/article/details/129755471