欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > springboot如何接入阿里云短信

springboot如何接入阿里云短信

2024/10/25 23:31:27 来源:https://blog.csdn.net/weixin_43394840/article/details/142948764  浏览:    关键词:springboot如何接入阿里云短信

登录阿里云开通短信模块
在这里插入图片描述
得到审核通过的签名
在这里插入图片描述
审核通过后,阿里云会赠送一条验证码模板,可以直接使用,如果有其他业务情况,可自行申请
在这里插入图片描述
引入阿里云短信依赖
pom.xml

<!--引入阿里云短信-->
<dependency><groupId>com.aliyun</groupId><artifactId>dysmsapi20170525</artifactId><version>2.0.18</version>
</dependency>

短信类代码如下:

public class SendMsg {private static final String accessKeyId = "你的KeyId";private static final String accessKeySecret = "你的KeySecret";/*** 使用AK&SK初始化账号Client** @return Client* @throws Exception*/public static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()// 您的 AccessKey ID.setAccessKeyId(accessKeyId)// 您的 AccessKey Secret.setAccessKeySecret(accessKeySecret);// 访问的域名config.endpoint = "dysmsapi.aliyuncs.com";return new com.aliyun.dysmsapi20170525.Client(config);}/*** 发送短信验证码**/public static boolean send(String mobies, String content) {try {com.aliyun.dysmsapi20170525.Client client = SendMsg.createClient();com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest();sendSmsRequest.setSignName("你的短信去签名,例如【中国移动】").setTemplateCode("你的短信模板code").setPhoneNumbers(mobies).setTemplateParam("{\"code\":\"" + content + "\"}");com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();// 复制代码运行请自行打印 API 的返回值SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);if ("OK".equals(response.getBody().getCode())) {return true;} else {System.out.println(response.getBody().getCode());return false;}} catch (TeaException error) {// 如有需要,请打印 errorcom.aliyun.teautil.Common.assertAsString(error.message);error.printStackTrace();return false;} catch (Exception _error) {TeaException error = new TeaException(_error.getMessage(), _error);// 如有需要,请打印 errorcom.aliyun.teautil.Common.assertAsString(error.message);error.printStackTrace();return false;}}
}

最终效果:
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com