Springboot整合Mail进行邮箱验证码注册

一、导入依赖

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

二、application.yml配置

spring:
  mail:
    host: smtp.qq.com
    port: 465
    username: 你的qq邮箱
    password: 你的qq邮箱授权码
    protocol: smtps
    default-encoding: UTF-8 #默认编码格式
    properties:
      mail:
        debug: true #启动debug调试
        smtp:
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory #SSL连接配置

Spring Mail的配置信息,用于设置邮件发送相关参数。

  • host: SMTP服务器的地址,这里使用QQ邮箱的SMTP服务器地址。
  • port: SMTP服务器监听的端口,默认为25,但QQ邮箱SMTP服务器采用SSL加密传输需要使用465端口。
  • username: 发送邮件的邮箱账号,这里填写QQ邮箱的账号。
  • password: 发送邮件的邮箱账号的授权码,用于验证邮箱身份,这里也填写QQ邮箱的账号的授权码。
  • protocol: 使用协议类型,这里选择smtps,即SMTP-over-SSL。
  • default-encoding: 默认编码格式,这里设置为UTF-8。
  • debug: 是否启动调试模式,当设置为true时会打印出更多调试信息。
  • properties: 设定额外的属性,这里设置了mailsmtp两个属性,socketFactory则对应SSL连接所需的类。

三、EmailService代码解读

@Service
public class EmailService {

创建一个名为EmailService的服务类。

@Autowired
private JavaMailSender mailSender;

使用Spring的自动装配(Autowired)特性注入一个JavaMailSender实例作为依赖项。JavaMailSender是用于发送邮件的Spring框架中的接口。

@Value("${spring.mail.username}")
private String from;

使用注释值(Value)来从配置文件中读取属性值,这里指的是spring.mail.username的值并将其变量化成from

public void sendMail(String to, String subject, String content) throws MessagingException {

在服务类中定义名为sendMail的方法,该方法接收三个参数(tosubjectcontent)并且可以抛出MessagingException异常。

MimeMessage message = mailSender.createMimeMessage();

创建邮件消息对象message,使用注入的mailSender的实例方法createMimeMessage()来创建相应的MIME消息。

MimeMessageHelper helper = new MimeMessageHelper(message, true);

创建一个帮助程序对象helper并将上述邮件消息message与之关联。true表示需要支持附件,否则设为false。

helper.setFrom(from);

设置发件人信息,在此处由变量from表示。

helper.setTo(to);

设置收件人信息,该信息由传入的参数to表示。

helper.setSubject(subject);

设置邮件主题,该主题由传入的参数subject表示。

helper.setText(content, true);

设置邮件正文,并指示内容是否为HTML格式。内容是由传入的参数 content表示的。

mailSender.send(message);

发送邮件,使用注入的mailSender实例的方法send()来将构造好的message对象发送。

四、VerificationCodeUtils随机验证码代码解读

public class VerificationCodeUtils {

这一行声明一个公共类(public class)VerificationCodeUtils。

    public static String generateCode(int length) {

这一行是声明一个公共的静态方法(public static method),名称为generateCode,返回类型为字符串(String),其中有一个参数,名称为length,表示生成的验证码的长度。

        StringBuilder s = new StringBuilder();

这一行是声明一个空白的字符串构建器(StringBuilder),用于存储生成的验证码。

        Random random = new Random();

这一行是声明一个随机数生成器(Random),用来产生随机数字。

        for (int i = 0; i < length; i++) {
            int n = random.nextInt(10);
            s.append(n);
        }

这一段是循环生成随机数字,并将其添加到指定长度的字符串构建器中。

        return s.toString();
    }
}

五、controller层代码解读

@Autowired
private EmailService emailService;

这行代码使用Spring的依赖注入自动将EmailService类的实例注入到emailService变量中。

private final Map<String, String> emailCodeMap = new ConcurrentHashMap<>(16);

这行代码声明一个并发哈希映射对象,用于存储邮箱验证码的键值对信息。

@PostMapping("/register")
public ApiResponse<String> register(@RequestBody Mail mail) throws MessagingException {

这行代码通过PostMapping注解配置了一个基于HTTP POST方法的请求处理,当收到路径为“/register”的请求时,它会将请求体反序列化成Mail类型的mail参数。ApiResponse是响应结果的数据类型,其中ResponseCode.SUCCESS表示成功状态码,"验证码已发送"是结果消息的内容。

String code = VerificationCodeUtils.generateCode(6);

这行代码调用VerificationCodeUtils工具类的generateCode方法生成一个6位数字的随机验证码,并将其保存在code变量中。

String subject = "注册验证码";
String content = "尊敬的用户,您的验证码为:" + code;
emailService.sendMail(mail.email, subject, content);

这三行代码设置邮件主题和内容,然后使用调用EmailService的sendMail方法将邮件发送给指定的邮箱(mail.email),以及验证码的message。

emailCodeMap.put(mail.email, code);

这行代码将(邮箱,验证码)键值对信息放入emailCodeMap哈希映射中。

return new ApiResponse<>(ResponseCode.SUCCESS,"验证码已发送");

最后,这行代码返回ApiResponse对象,该对象包含了响应结果的状态码和消息内容。

六、整体代码

  @Autowired
    private EmailService emailService;

    // 存储已发送的验证码
    private final Map<String, String> emailCodeMap = new ConcurrentHashMap<>(16);

    @PostMapping("/register")
    public ApiResponse<String> register(@RequestBody Mail mail)  throws MessagingException {
        // 检查邮箱是否已被注册
        // ...

        // 生成验证码
        String code = VerificationCodeUtils.generateCode(6);

        // 发送邮件
        String subject = "注册验证码";
        String content = "尊敬的用户,您的验证码为:" + code;
        emailService.sendMail(mail.email, subject, content);

        // 保存验证码
        emailCodeMap.put(mail.email, code);

       return new ApiResponse<>(ResponseCode.SUCCESS,"验证码已发送");
    }

@Data
public class Mail {
    public String email;
    public String username;
    public String password;
}


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

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件
     *
     * @param to      收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendMail(String to, String subject, String content) throws MessagingException {
        // 创建邮件消息
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        // 发送邮件
        mailSender.send(message);
    }
}

public class VerificationCodeUtils {
    /**
     * 生成随机验证码
     *
     * @param length 验证码长度
     * @return 验证码
     */
    public static String generateCode(int length) {
        StringBuilder s = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int n = random.nextInt(10);
            s.append(n);
        }
        return s.toString();
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是一个简单的Spring Boot邮箱验证注册登录的实现示例: 1. 引入依赖 在pom.xml中加入以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 配置邮箱信息 在application.properties或application.yml文件中添加邮件相关配置信息: ```properties # 邮箱服务器地址 spring.mail.host=smtp.qq.com # 邮箱服务器端口 spring.mail.port=587 # 邮箱账号 spring.mail.username=your_email@qq.com # 邮箱授权码,非邮箱密码 spring.mail.password=your_email_password # 是否启用ssl spring.mail.properties.mail.smtp.starttls.enable=true ``` 3. 编写注册登录接口 编写一个简单的RestController类,包含以下接口: - 发送验证码接口:根据邮箱地址发送验证码。 - 注册接口:根据邮箱地址和验证进行注册。 - 登录接口:根据邮箱地址和密码进行登录。 ```java @RestController public class UserController { @Autowired private JavaMailSender mailSender; // 发送验证码接口 @PostMapping("/sendCode") public String sendCode(@RequestParam String email) { String code = generateCode(); // 发送邮件 SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("your_email@qq.com"); message.setTo(email); message.setSubject("验证码"); message.setText("您的验证码是:" + code); mailSender.send(message); return code; } // 注册接口 @PostMapping("/register") public String register(@RequestParam String email, @RequestParam String code) { // 校验验证码 // 根据邮箱验证进行注册 return "注册成功"; } // 登录接口 @PostMapping("/login") public String login(@RequestParam String email, @RequestParam String password) { // 根据邮箱和密码进行登录 return "登录成功"; } // 生成随机验证码 private String generateCode() { String codeChars = "0123456789"; StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 6; i++) { int index = random.nextInt(codeChars.length()); sb.append(codeChars.charAt(index)); } return sb.toString(); } } ``` 4. 测试接口 使用Postman等工具测试上述接口。例如: - 发送验证码接口:POST http://localhost:8080/sendCode?email=your_email@qq.com - 注册接口:POST http://localhost:8080/register?email=your_email@qq.com&code=123456 - 登录接口:POST http://localhost:8080/login?email=your_email@qq.com&password=your_password 以上示例仅为参考,实际应用中还需要进行参数校验、异常处理等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

吉屋安

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

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

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

打赏作者

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

抵扣说明:

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

余额充值