0
点赞
收藏
分享

微信扫一扫

在SpringBoot 和 Vue的项目中使用SpringBoot-email

在SpringBoot + Vue的项目中使用SpringBoot-email发送验证码,具体步骤如下:

  1. 添加依赖

首先需要在pom.xml文件中添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

  1. 配置邮箱信息

在application.properties或application.yml文件中配置邮箱相关信息,例如:

spring.mail.host=smtp.example.com
spring.mail.username=example@example.com
spring.mail.password=yourpassword
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.example.com

需要将上述参数替换为实际的邮箱地址、密码、host等信息。

  1. 创建EmailService类

创建一个名为EmailService的类,用于封装邮件发送的逻辑。可以使用JavaMailSender类来发送邮件,示例代码如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender javaMailSender;

    public void sendSimpleMessage(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        javaMailSender.send(message);
    }

    @Bean
    public JavaMailSender getJavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.example.com");
        mailSender.setPort(587);

        mailSender.setUsername("example@example.com");
        mailSender.setPassword("yourpassword");

        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.debug", "true");

        return mailSender;
    }
}

其中,sendSimpleMessage方法用于发送简单邮件,接收to(收件人邮箱)、subject(主题)和text(正文)三个参数,并使用JavaMailSender发送邮件。getJavaMailSender方法用于配置JavaMailSender实例,也可以将其单独提取出来放到配置文件中。

  1. 生成验证码

使用Java自带的Random类生成一个随机的四位数作为验证码。

import java.util.Random;

public class Utils {
    public static String generateVerificationCode() {
        Random random = new Random();
        int code = random.nextInt(8999) + 1000;
        return String.valueOf(code);
    }
}

  1. 调用EmailService发送邮件

在注册账号时,生成一个验证码,并将验证码发送至用户邮箱。可以将验证码存储在Redis中,这样做的好处是可以避免用户恶意频繁请求验证码。

@RestController
public class RegisterController {
    @Autowired
    private EmailService emailService;
    
    @PostMapping("/register")
    public Result register(@RequestParam String email) {
        try {
            // 生成验证码
            String code = Utils.generateVerificationCode();
            // 将验证码存储到Redis中
            redisTemplate.opsForValue().set(redisKey, code, 5, TimeUnit.MINUTES);
            // 发送注册邮件
            emailService.sendSimpleMessage(email, "注册验证码", "您的验证码是:" + code);
            return new Result(Result.SUCCESS, "验证码已发送至您的邮箱");
        } catch (Exception e) {
            return new Result(Result.ERROR, "发送验证码失败");
        }
    }
}

  1. 在Vue前端页面中接收验证码

在Vue前端页面中,用户输入邮箱并点击发送验证码按钮时,向后端发送请求,并接收后端返回的数据(即“验证码已发送”或“发送验证码失败”)。

<template>
  <div>
    <el-input v-model="email" placeholder="请输入邮箱"></el-input>
    <el-button type="primary" @click="sendCode" :disabled="disableSend">发送验证码</el-button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      email: '',
      disableSend: false
    }
  },
  methods: {
    sendCode () {
      this.disableSend = true
      axios.post('/register', { email: this.email }).then(res => {
        if (res.data.status === 'success') {
          this.$message.success(res.data.msg)
        } else {
          this.$message.error(res.data.msg)
        }
        this.disableSend = false
      }).catch(error => {
        console.log(error)
        this.$message.error('发送验证码失败')
        this.disableSend = false
      })
    }
  }
}
</script>

以上就是在SpringBoot+Vue的项目中使用SpringBoot-email发送用户注册账号时的验证码的详细介绍。

举报

相关推荐

0 条评论