当前位置: 首页 > news >正文

springboot 如何实现发送短信

在 Spring Boot 中实现发送短信通常借助第三方短信服务提供商,如阿里云短信服务、腾讯云短信服务、华为云短信服务等。下面以阿里云短信服务为例,详细介绍在 Spring Boot 项目中实现发送短信的步骤。

1. 开通阿里云短信服务并获取相关信息

  • 注册阿里云账号:如果还没有阿里云账号,需要先进行注册。
  • 开通短信服务:登录阿里云控制台,开通短信服务,并完成相关的配置,如签名、模板的申请和审核。
  • 获取 AccessKey:在阿里云控制台的 AccessKey 管理页面创建并获取 AccessKey ID 和 AccessKey Secret,这两个信息用于身份验证。

2. 添加依赖

在 pom.xml 中添加阿里云短信服务的 Java SDK 依赖:

收起

xml

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 阿里云短信服务 SDK -->
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>dysmsapi20170525</artifactId>
        <version>2.0.22</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>tea-openapi</artifactId>
        <version>0.2.1</version>
    </dependency>
</dependencies>

3. 配置阿里云短信服务信息

在 application.properties 或 application.yml 中配置阿里云短信服务的相关信息:

收起

properties

aliyun.sms.access-key-id=your-access-key-id
aliyun.sms.access-key-secret=your-access-key-secret
aliyun.sms.sign-name=your-sign-name
aliyun.sms.template-code=your-template-code

将 your-access-key-idyour-access-key-secret 替换为你在阿里云获取的 AccessKey ID 和 AccessKey Secretyour-sign-name 替换为申请通过的短信签名,your-template-code 替换为申请通过的短信模板代码。

4. 创建短信发送工具类

创建一个工具类来封装短信发送的逻辑:

收起

java

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SmsSender {

    @Value("${aliyun.sms.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.sms.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.sign-name}")
    private String signName;

    @Value("${aliyun.sms.template-code}")
    private String templateCode;

    public boolean sendSms(String phoneNumber, Map<String, String> templateParams) {
        try {
            // 创建 Config 对象并设置 AccessKey ID 和 AccessKey Secret
            Config config = new Config()
                   .setAccessKeyId(accessKeyId)
                   .setAccessKeySecret(accessKeySecret);
            // 访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            // 创建短信服务客户端
            Client client = new Client(config);

            // 创建短信发送请求对象
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                   .setPhoneNumbers(phoneNumber)
                   .setSignName(signName)
                   .setTemplateCode(templateCode)
                   .setTemplateParam(com.alibaba.fastjson.JSON.toJSONString(templateParams));

            // 发送短信
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

            // 判断短信是否发送成功
            return "OK".equals(sendSmsResponse.getBody().getCode());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

5. 创建控制器进行测试

创建一个控制器类,在其中调用短信发送工具类来发送短信:

收起

java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class SmsController {

    @Autowired
    private SmsSender smsSender;

    @GetMapping("/sendSms")
    public String sendSms(@RequestParam String phoneNumber) {
        // 假设短信模板中有一个参数 code 用于传递验证码
        Map<String, String> templateParams = new HashMap<>();
        templateParams.put("code", "123456");

        boolean result = smsSender.sendSms(phoneNumber, templateParams);
        if (result) {
            return "短信发送成功";
        } else {
            return "短信发送失败";
        }
    }
}

6. 测试短信发送功能

启动 Spring Boot 应用程序,访问 http://localhost:8080/sendSms?phoneNumber=your-phone-number,将 your-phone-number 替换为实际要接收短信的手机号码。如果一切配置正确,该手机号码将收到一条包含验证码的短信。

注意事项

  • 确保申请的短信签名和模板已通过审核,否则短信无法发送成功。
  • 不同的短信模板可能有不同的参数要求,需要根据实际情况修改 templateParams 中的参数。
  • 阿里云短信服务有一定的使用限制和费用,需要关注相关的使用规则和计费标准。

相关文章:

  • 什么是 Ribbon?
  • WordPress平台如何接入Deepseek,有效提升网站流量
  • Deepseek引爆AI热潮 防静电地板如何守护数据中心安全
  • 通义灵码在跨领域应用拓展之物联网篇
  • 蓝桥杯第十六届嵌入式模拟编程题解析
  • Android TextView 使用.9图片文字不展示
  • 计算机视觉算法实战——跌倒检测(主页有源码)
  • 【前端】【功能函数】treeMapEach,对每个节点进行自定义转换的实用函数
  • 深入理解 CSS pointer-events: none:穿透点击的魔法
  • 前端兼容处理接口返回的文件流或json数据
  • C++ Primer 容器适配器
  • java基础学习
  • SQL笔记#函数、谓词、CASE表达式
  • JavaScript 中的逻辑运算符
  • 项目实战--网页五子棋(匹配模块)(5)
  • 【网络安全 | 漏洞挖掘】Stripe 子系统 TaxJar 的 ATO 漏洞挖掘之旅
  • 【第五节】C++设计模式(创建型模式)-Prototype(原型)模式
  • 【NLP 23、预训练语言模型】
  • 码率和采样率
  • UE_C++ —— Gameplay Modules
  • 海南教育学会网站建设/怎么创建网站免费建立个人网站
  • 网站开发工程师岗位描述/百度导航最新版本
  • 深圳 做网站 互联/自动秒收录网
  • 国外做滑板网站/免费的seo优化工具
  • 东莞疫情感染人数/google移动服务应用优化
  • django 开放api 做网站/免费seo视频教学