添加pom.xml依赖

<dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.0.6</version>
</dependency>
<dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-dysmsapi</artifactId><version>1.1.0</version>
</dependency>

阿里云短信工具类

public class AliYunSmsUtils {//阿里云短信请求地址private static final String ALIYUN_IP = "dysmsapi.aliyuncs.com";//阿里云短信服务器区域类型private static final String REGION_ID = "cn-hangzhou";//阿里云短信服务版本号private static final String VERSION = "2017-05-25";/*** 所有请求通用参数** @param smsInterfaceType* @return*/private static CommonRequest getCommonRequest(SmsInterfaceType smsInterfaceType) {//初始化设置阿里云短信发送消息体CommonRequest commonRequest = new CommonRequest();//设置阿里云短信消息体请求类型commonRequest.setMethod(MethodType.POST);//设置阿里云短信消息体接口调用ip地址commonRequest.setDomain(ALIYUN_IP);//设置阿里云短信服务版本commonRequest.setVersion(VERSION);//设置阿里云短信请求接口类型commonRequest.setAction(smsInterfaceType.getType());//设置阿里云短信服务器区域类型commonRequest.putQueryParameter("RegionId", REGION_ID);return commonRequest;}/*** 校验短信模板申请请求参数* @param templateNameRequest*/public static void validatedTemplateNameRequest(TemplateNameRequest templateNameRequest) {if(StringUtils.isBlank(templateNameRequest.getAccessKeyID())){throw new ServiceException("accessKeyID不能为空");}if(StringUtils.isBlank(templateNameRequest.getAccessKeySecret())){throw new ServiceException("accessKeySecret不能为空");}if(StringUtils.isBlank(templateNameRequest.getTemplateName())){throw new ServiceException("模板名称不能为空");}if(ObjectUtil.isNull(templateNameRequest.getSmsTemplateType())){throw new ServiceException("模板类型不能为空");}if(StringUtils.isBlank(templateNameRequest.getTemplateContent())){throw new ServiceException("模板格式内容不能为空");}if(StringUtils.isBlank(templateNameRequest.getRemark())){throw new ServiceException("说明不能为空");}}/*** 申请短信模板** @param templateNameRequest 短信模板申请参数* @return*/public static Result startAddSmsTemplate(TemplateNameRequest templateNameRequest) {//参数校验validatedTemplateNameRequest(templateNameRequest);//初始化设置阿里云短信发送消息体CommonRequest commonRequest = getCommonRequest(SmsInterfaceType.ADD_SMS_TEMPLATE);//初始化阿里云短信接收结果消息体CommonResponse commonResponse = null;//初始化设置阿里云用户唯一标识和短信服务器区域类型(用来认证用户的)DefaultProfile defaultProfile = DefaultProfile.getProfile(REGION_ID, templateNameRequest.getAccessKeyID(), templateNameRequest.getAccessKeySecret());IAcsClient iAcsClient = new DefaultAcsClient(defaultProfile);//设置阿里云短信模板申请类型commonRequest.putQueryParameter("TemplateType", String.valueOf(templateNameRequest.getSmsTemplateType().getTemplateTypeId()));//设置阿里云短信模板申请名称commonRequest.putQueryParameter("TemplateName", templateNameRequest.getTemplateName());//设置阿里云短信模板申请格式内容commonRequest.putQueryParameter("TemplateContent", templateNameRequest.getTemplateContent());//设置阿里云短信模板签名commonRequest.putQueryParameter("SignName", templateNameRequest.getSignName());//设置阿里云短信模板申请说明commonRequest.putQueryParameter("Remark", templateNameRequest.getRemark());try {commonResponse = iAcsClient.getCommonResponse(commonRequest);} catch (ClientException e) {e.printStackTrace();return Result.error("网络错误");}if(commonResponse.getHttpStatus()==200){JSON json = JSONUtil.parse(commonResponse.getData());if("OK".equals(json.getByPath("Code"))){Map<String,Object> map = new HashMap<>();map.put("TemplateCode",json.getByPath("TemplateCode"));return Result.success(200, "模板已提交申请,请等待审核", map);}return Result.error(json.getByPath("Message").toString());}return Result.error("网络错误");}/*** 查询指定code的短信模板** @param smsRequest 通用请求* @return*/public static Result startQuerySmsTemplate(SmsRequest smsRequest) {if (StringUtils.isBlank(smsRequest.getTemplateCode())) {throw new ServiceException("模板code不能为空");}//初始化设置阿里云短信发送消息体CommonRequest commonRequest = getCommonRequest(SmsInterfaceType.QUERY_SMS_TEMPLATE);//初始化阿里云短信接收结果消息体CommonResponse commonResponse = null;//初始化设置阿里云用户唯一标识和短信服务器区域类型(用来认证用户的)DefaultProfile defaultProfile = DefaultProfile.getProfile(REGION_ID, smsRequest.getAccessKeyID(), smsRequest.getAccessKeySecret());IAcsClient iAcsClient = new DefaultAcsClient(defaultProfile);//设置阿里云短信服务器区域类型commonRequest.putQueryParameter("RegionId", REGION_ID);//设置要查询的短信签名名称commonRequest.putQueryParameter("TemplateCode", smsRequest.getTemplateCode());try {commonResponse = iAcsClient.getCommonResponse(commonRequest);} catch (ClientException e) {e.printStackTrace();return Result.error("网络错误");}if(commonResponse.getHttpStatus()==200){JSON json = JSONUtil.parse(commonResponse.getData());if("OK".equals(json.getByPath("Code"))){Map<String,Object> map = new HashMap<>();map.put("TemplateCode",json.getByPath("TemplateCode"));map.put("TemplateName",json.getByPath("TemplateName"));map.put("TemplateContent",json.getByPath("TemplateContent"));map.put("TemplateType",json.getByPath("TemplateType"));map.put("CreateDate",json.getByPath("CreateDate"));map.put("Reason",json.getByPath("Reason"));map.put("TemplateStatus",json.getByPath("TemplateStatus"));return Result.success(200, "查询成功",map);}return Result.error(json.getByPath("Message").toString());}return Result.error("网络错误");}/*** 根据模板code删除短信模板** @param templateNameRequest 通用请求* @return*/public static Result startDeleteSmsTemplate(TemplateNameRequest templateNameRequest) {if (StringUtils.isBlank(templateNameRequest.getTemplateCode())) {throw new ServiceException("模板code不能为空");}//初始化设置阿里云短信发送消息体CommonRequest commonRequest = getCommonRequest(SmsInterfaceType.DELETE_SMS_TEMPLATE);//初始化阿里云短信接收结果消息体CommonResponse commonResponse = null;//初始化设置阿里云用户唯一标识和短信服务器区域类型(用来认证用户的)DefaultProfile defaultProfile = DefaultProfile.getProfile(REGION_ID, templateNameRequest.getAccessKeyID(), templateNameRequest.getAccessKeySecret());IAcsClient iAcsClient = new DefaultAcsClient(defaultProfile);//设置要删除的短信模板签名名称commonRequest.putQueryParameter("TemplateCode", templateNameRequest.getTemplateCode());try {commonResponse = iAcsClient.getCommonResponse(commonRequest);} catch (ClientException e) {e.printStackTrace();return Result.error("网络错误");}if(commonResponse.getHttpStatus()==200){JSON json = JSONUtil.parse(commonResponse.getData());if("OK".equals(json.getByPath("Code"))){Map<String,Object> map = new HashMap<>();map.put("TemplateCode",json.getByPath("TemplateCode"));return Result.success(200, "短信模板删除成功",map);}return Result.error(json.getByPath("Message").toString());}return Result.error("网络错误");}/*** 发送短信** @param smsRequest 通用短信发送参数* @return*/public static Result startSendSms(SmsRequest smsRequest) {//初始化设置阿里云短信发送消息体CommonRequest commonRequest = getCommonRequest(SmsInterfaceType.SEND_SMS);//初始化阿里云短信接收结果消息体CommonResponse commonResponse = null;//初始化设置阿里云用户唯一标识和短信服务器区域类型(用来认证用户的)DefaultProfile defaultProfile = DefaultProfile.getProfile(REGION_ID, smsRequest.getAccessKeyID(), smsRequest.getAccessKeySecret());IAcsClient iAcsClient = new DefaultAcsClient(defaultProfile);//设置接收短信的手机号码commonRequest.putQueryParameter("PhoneNumbers", smsRequest.getPhoneNumber());//设置阿里云短信模板签名commonRequest.putQueryParameter("SignName", smsRequest.getSignName());//设置阿里云短信模板codecommonRequest.putQueryParameter("TemplateCode", smsRequest.getTemplateCode());//设置短信内容commonRequest.putQueryParameter("TemplateParam", parsingKeyValue(smsRequest.getMapContent()));try {//确认发送短信commonResponse = iAcsClient.getCommonResponse(commonRequest);} catch (ClientException e) {e.printStackTrace();return Result.error("网络错误");}//参数配置校验未通过错误if(commonResponse.getHttpStatus()==200){JSON json = JSONUtil.parse(commonResponse.getData());if("OK".equals(json.getByPath("Code"))){return Result.success("发送成功");}return Result.error(json.getByPath("Message").toString());}return Result.error("网络错误");}/*** 把短信内容进行排版,排成阿里云要求的格式** @param mapContent* @return*/private static String parsingKeyValue(Map<String, String> mapContent) {StringBuilder stringBuilder = new StringBuilder();stringBuilder.append("{");for (String key : mapContent.keySet()) {stringBuilder.append("'" + key + "':'" + mapContent.get(key) + "',");}return stringBuilder.substring(0, stringBuilder.length() - 1) + "}";}/*** 批量发送短信** @param batchSmsRequest 通用请求* @return*/public static Result startSendBatchSms(BatchSmsRequest batchSmsRequest) {//初始化设置阿里云短信发送消息体CommonRequest commonRequest = getCommonRequest(SmsInterfaceType.BATCH_SEND_SMS);//初始化阿里云短信接收结果消息体CommonResponse commonResponse = null;//初始化设置阿里云用户唯一标识和短信服务器区域类型(用来认证用户的)DefaultProfile defaultProfile = DefaultProfile.getProfile(REGION_ID, batchSmsRequest.getAccessKeyID(), batchSmsRequest.getAccessKeySecret());IAcsClient iAcsClient = new DefaultAcsClient(defaultProfile);//设置接收短信的手机号码commonRequest.putQueryParameter("PhoneNumberJson", JSONUtil.toJsonStr(batchSmsRequest.getPhoneNumber()));//设置阿里云短信模板签名commonRequest.putQueryParameter("SignNameJson", JSONUtil.toJsonStr(batchSmsRequest.getSignName()));//设置阿里云短信模板codecommonRequest.putQueryParameter("TemplateCode", batchSmsRequest.getTemplateCode());//设置短信内容commonRequest.putQueryParameter("TemplateParamJson", JSONUtil.parseArray(batchSmsRequest.getMapContent()).toString());try {//确认发送短信commonResponse = iAcsClient.getCommonResponse(commonRequest);} catch (ClientException e) {e.printStackTrace();return Result.error("网络错误");}if(commonResponse.getHttpStatus()==200){JSON json = JSONUtil.parse(commonResponse.getData());if("OK".equals(json.getByPath("Code"))){return Result.success("发送成功");}return Result.error(json.getByPath("Message").toString());}return Result.error("网络错误");}
}

对应的参数类以及枚举类

import lombok.AllArgsConstructor;
import lombok.Getter;/*** 短信请求接口类型* @author zhouhz*/
@Getter
@AllArgsConstructor
public enum SmsInterfaceType {//申请短信模板签名ADD_SMS_SIGN("AddSmsSign"),//申请短信模板ADD_SMS_TEMPLATE("AddSmsTemplate"),//删除短信模板签名DELETE_SMS_SIGN("DeleteSmsSign"),//删除短信模板DELETE_SMS_TEMPLATE("DeleteSmsTemplate"),//修改未审核通过的短信模板签名,重新申请审核MODIFY_SMS_SIGN("ModifySmsSign"),//修改未审核通过的短信模板,重新申请审核MODIF_SMS_TEMPLATE("ModifySmsTemplate"),//查询所有短信模板签名QUERY_SMS_SIGN("QuerySmsSign"),//查询所有短信模板QUERY_SMS_TEMPLATE("QuerySmsTemplate"),//查询所有已发送的短信QUERY_SEND_DETAILS("QuerySendDetails"),//发送短信SEND_SMS("SendSms"),//批量发送短信BATCH_SEND_SMS("SendBatchSms");private final String type;
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;/*** 短信模板申请参数* @author zhouhz*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class TemplateNameRequest {private static final long serialVersionUID = 1L;/*** 阿里云用户AccessKey ID*/private String accessKeyID;/*** 阿里云用户AccessKey Secret*/private String accessKeySecret;/*** 模板类型*/private SmsTemplateType smsTemplateType;/*** 模板code*/private String templateCode;/*** 模板名称*/private String templateName;/*** 短信模板格式内容,对应的参数用 ${name} 表示,对应发送短信时候的内容参数*/private String templateContent;/*** 签名*/private String signName;/*** 短信模板申请说明*/private String remark;
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;import java.util.Map;/*** 单一短信请求参数* @author zhouhz*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class SmsRequest {private static final long serialVersionUID = 1L;/*** 阿里云用户AccessKey ID*/private String accessKeyID;/*** 阿里云用户AccessKey Secret*/private String accessKeySecret;/*** 手机号*/private String phoneNumber;/*** 签名*/private String signName;/*** 模板code*/private String templateCode;/*** 短信内容,key是对应短信模板的参数字段,value是字段对应的内容*/private Map<String,String> mapContent;}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;import java.util.List;
import java.util.Map;/*** 批量短信请求参数* @author zhouhz*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class BatchSmsRequest {private static final long serialVersionUID = 1L;/*** 阿里云用户AccessKey ID*/private String accessKeyID;/*** 阿里云用户AccessKey Secret*/private String accessKeySecret;/*** 手机号*/private List<String> phoneNumber;/*** 签名*/private List<String> signName;/*** 模板code*/private String templateCode;/*** 短信内容,key是对应短信模板的参数字段,value是字段对应的内容*/private List<Map<String,String>> mapContent;}

完整的接口请求

Controller层
@Autowired
private AliDayuConfig aliDayuConfig;@ApiOperation("申请短信模板")
@PostMapping("/startAddSmsTemplate")
public Result startAddSmsTemplate(@RequestBody TemplateNameRequest templateNameRequest){templateNameRequest.setAccessKeyID(aliDayuConfig.getAccessKeyId());templateNameRequest.setAccessKeySecret(aliDayuConfig.getAccessKeySecret());templateNameRequest.setSignName(aliDayuConfig.getSignName());try{//参数校验AliYunSmsUtils.validatedTemplateNameRequest(templateNameRequest);}catch (Exception e){return Result.error(e.getMessage());}return AliYunSmsUtils.startAddSmsTemplate(templateNameRequest);
}

读取配置文件类

@Data
@Component
public class AliDayuConfig {@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;}

配置文件

aliyun:sms:access-key-id: #idaccess-key-secret: #secretsign-name: #签名

JAVA 实现阿里云短信申请模板以及批量发送短信相关推荐

  1. Java 对接 阿里云 的短信服务完成短信的发送与查询

    一.开通阿里云短信服务,为开发时需要用到的信息做准备 1.注册或者使用自己的支付宝账号登录阿里云官网 2.搜索并找到短信服务,进行开通(开通是不要钱的,发送短信的时候才需要钱) 3.注册自己的短信签名 ...

  2. java对接阿里云短信服务详解(验证码,推广短信,通知短信)

    前言 小前提: - java:springboot框架,maven版本管理. - 阿里云:有账号,已经进行实名认证. java对接阿里云短信服务详解(验证码,推广短信,通知短信) 前言 1. 登录阿里 ...

  3. Java调用阿里云短信接口,发送短信

    Java调用阿里云短信接口,发送短信 1.短信服务这个很简单,只需要知道accessKeyId(AK).accessKeySecret(SK).短信签名.短信模板即可. 2.域名和产品名称是固定的,使 ...

  4. (短信服务)java SpringBoot 阿里云短信功能实现发送手机验证码

    一.阿里云准备工作 1.阿里云短信服务-注册账号 阿里云官网: https://www.aliyun.com/ 点击官网首页注册按钮. 2.阿里云短信服务-设置短信签名(阿里云提供测试的签名,暂时可以 ...

  5. Java后端阿里云短信平台发送短信

    最近做了关于阿里云平台发送短信的功能,记录下代码方便以后查阅: @Service public class ALiYunSMSServiceImpl implements ALiYunSMSServi ...

  6. java实现阿里云短信验证注册--详细教程

    java实现阿里云短信验证注册–详细教程 .项目中先引入依赖 <!--阿里云短信包--><dependency><groupId>com.aliyun</gr ...

  7. 个人永久性免费-Excel催化剂功能第85波-灵活便捷的批量发送短信功能(使用腾讯云接口)...

    微信时代的今天,短信一样不可缺席,大系统都有集成短信接口. 若只是临时用一下,若能够直接在Excel上加工好内容就可以直接发送,这些假设在此篇批量群发短信功能中都为大家带来完美答案. 业务场景 不多说 ...

  8. 2022阿里云学生服务器申请地址购买攻略及配置选择

    简介: 阿里云学生服务器优惠价格9.5元/月,可选ECS云服务器和轻量应用服务器,2020阿里云学生服务器「云翼计划」依旧可以申请 2020阿里云学生服务器优惠申请云翼计划,学生群体9.5元获得一台阿 ...

  9. Java使用阿里云OSS对象存储上传图片

    示例说明   该案例是OSS Java SDK的示例程序,您可以修改endpoint.accessKeyId.accessKeySecret.bucketName后直接运行. 本示例中的并不包括OSS ...

最新文章

  1. Hibernate和Mysql5.1以上版本创建表出错 type=InnDB
  2. IDEA中maven项目导jar包太慢
  3. python下载图片、已知url_python 爬虫之requests爬取页面图片的url,并将图片下载到本地...
  4. oracle 11g goldengate与oracle 11g数据同步
  5. NgRx createSelector 工具函数的三个类型参数
  6. oracle exp调过坏块,无备份坏块处理(跳过方式)
  7. 如果你正处于迷茫期,那就来做这份工作吧!
  8. el-table使用图片实例代码
  9. python-整理--连接MSSQL
  10. Mybatis批量保存Clob类型时ORA-01461: can bind a LONG value only for insert into a LONG column报错解决方法
  11. 海拔高度与大气密度的关系函数
  12. AcroFields设置PDF文本域
  13. 信任,是从心底产生的感觉
  14. Facebook 如何管理 150亿张照片
  15. Liferay 6.2 改造系列之三:删除Docbar中的添加内容功能
  16. NAMD跑分子动力学模拟出现的一些问题(更新中)
  17. Python3 math模块以及运算优先级
  18. 工作中常用的前端知识总结
  19. UCOSIII任务调度和任务切换
  20. Mysql 8配置驱动

热门文章

  1. 学会记忆--学会遗忘
  2. 产品Banner样式类型分析
  3. C语言包含特殊寄存器文件ch,c语言第二次实验报告 - osc_zfz30hgc的个人空间 - OSCHINA - 中文开源技术交流社区...
  4. 网站的养站(养蜘蛛)技巧
  5. cshop是什么开发语言_Fecshop 多语言
  6. 有哪些不错的电子书管理软件?免费项目管理软件推荐
  7. 鸽哒im即时通讯源码加教程
  8. 程序员加班看不上球赛崩溃,外卖小哥伸出援手:我帮你改代码
  9. texlive和texstudio安装及使用
  10. tomcat处理html流程,基于Tomcat运行HTML5 WebSocket echo实例详解