一篇文章带你学会springboot中发送邮箱验证码和手机验证码

一、需求

开发项目中很多场景需要使用邮箱发送验证码 和手机发送验证码功能。

阿里云邮箱注册地址:https://market.aliyun.com/products/57002003/cmapi00037170.html?spm=5176.2020520132.101.2.330c7218KMwlX4#sku=yuncode3117000002

阿里云手机短信购买地址: https://market.aliyun.com/products/57002003/cmapi00037170.html?spm=5176.2020520132.101.2.330c7218KMwlX4#sku=yuncode3117000002

二、代码功能

(0) 引入pom.xml依赖

  <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.16</version>
        </dependency>
 <!--使用邮箱服务 -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>

(1)UserController


package com.beiyou.controller;

import com.beiyou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;
    /** 发送邮箱验证码 */
    @GetMapping("/send/code")
    public Integer sendCode(String email) {
        return userService.sendCode(email);
    }
    /**发送手机验证码 */
    @GetMapping("/send/tel/code")
    public Integer sendTelCode(String tel){
        return userService.sendTelCode(tel);
    }

}

(2) UserService


package com.beiyou.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.smart.core.exception.BizException;
import com.beiyou.dao.UserDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserDao userDao;
    /**
     * 目前暂时将发送的邮箱和验证码存到map中 真正做项目是存到redis里
     */
    private static HashMap<String,Integer> emailMap=new HashMap();
    /** 
     * 发送邮箱验证码
     */
    public Integer sendCode(String email) {
        /**定义四位随机数 */
        int code = RandomUtil.randomInt(1000, 10000);
        /**这个对象记录了邮箱服务器的记录的信息 */
        MailAccount mailAccount = new MailAccount();
        /** smtp 表示协议 aliyun 表示邮箱类型,可以换成qq等  */
        mailAccount.setHost("smtp.aliyun.com");
        /** 默认端口为25 */
        mailAccount.setPort(25);
        /**
         * setAuth(boolean auth) 方法用于设置是否在进行邮件发送或接收时进行身份验证。
         * 当设置为 true 时,表示需要进行身份验证,这通常意味着在连接邮件服务器时会使用提供的用户名和密码进行登录。
         */
        mailAccount.setAuth(true);
        /** 用户设置发送人的地址*/
        mailAccount.setUser("814736551@aliyun.com");
        /** 用户设置发送人的地址*/
        mailAccount.setFrom("814736551@aliyun.com");
        /** 用户设置发送人的密码*/
        mailAccount.setPass("Huang814736551");
        MailUtil.send(mailAccount,email,"WMS系统验证码","验证码:"+code,false);
        emailMap.put(email,code);
        log.info("发送验证码成功");
        return 0;

    }

    /**
     * 发送手机验证码
     * @return
     */
    public Integer sendTelCode(String tel) {
        /**定义四位随机数 */
        int code = RandomUtil.randomInt(1000, 10000);
        String url = "https://dfsns.market.alicloudapi.com/data/send_sms";
        /**阿里云短信接口 自己掏钱买别用我的 */ 
        String appcode="8f8646c611914b5084c405a2671ddf49";
        emailMap.put(tel,code);
        String result = HttpRequest.post(url)
                /**头信息 APPCODE必须要有一个空格 */
                .header("Authorization", "APPCODE " + appcode)
                .body("content=code:" + code + "&template_id=TPL_0000&phone_number=" + tel)
                .execute().body();
        JSONObject object = JSONUtil.parseObj(result);
        if(!object.get("status").equals("OK")){
            log.error("发送验证码错误:{}",object.get("reason"));
            throw new BizException(404,"发送验证码错误");
        }
        return 0;


    }
}

三、打开接口调试工具进行调试

3.1 调试邮箱

 

  • 打开阿里云邮箱查看是否发送验证码

 

3.2 调试手机验证码

 

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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、付费专栏及课程。

余额充值