1、申请阿里云短信服务地址https://mns.console.aliyun.com/sms?spm=5176.2020520115.103.4.kh6K2x#/sms/Template
2、登录阿里云以后 点击短信 -->短信模板-->新建短信模板
3、添加模板名称。短信内容,申请说明,记住${code} 这里的code是变量,在代码中给予赋值。
4、coding ,参考阿里云短信api,说实话当时找了很久。现在整理下来不容易。下面这段代码,可以直接copy下来,修改里面的变量,和你的短信模板,就可以使用了
package com.aidongsports.utils;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.BatchSmsAttributes;
import com.aliyun.mns.model.MessageAttributes;
import com.aliyun.mns.model.RawTopicMessage;
import com.aliyun.mns.model.TopicMessage;
import java.util.List;
import java.util.Map;
/**
* Created by HONGLINCHEN on 2017/4/24.
*/
public class SmsUtils {
public static boolean sendMsg(String templateCode,Map
/**
* Step 1. 获取主题引用
* Access Key ID = LTAIGEwNE919qdk7
* Access Key Secret = mR4RPwfucRS4e1AqoT7iUJOLfK8fsf
* AppCode = 60b74516694144ca862b1f55e574006d
*/
CloudAccount account = new CloudAccount("LTAIGEwNE487qdk7", "mR4RPwfucRS4e1AqoTfsdfsdfsdff", "https://1759549822809348.mns.cn-hangzhou.aliyuncs.com/");
MNSClient client = account.getMNSClient();
CloudTopic topic = client.getTopicRef("test-sms-topic");//短信主题,可以在阿里云申请
/**
* Step 2. 设置SMS消息体(必须)
*
* 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
*/
RawTopicMessage msg = new RawTopicMessage();
msg.setMessageBody("sms-message");
/**
* Step 3. 生成SMS消息属性
*/
MessageAttributes messageAttributes = new MessageAttributes();
BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
// 3.1 设置发送短信的签名(SMSSignName)
batchSmsAttributes.setFreeSignName("上海****公司");//短信签名,可以在阿里云申请
// 3.2 设置发送短信使用的模板(SMSTempateCode)
batchSmsAttributes.setTemplateCode(templateCode);
// 3.3 设置发送短信所使用的模板中参数对应的值(在短信模板中定义的,没有可以不用设置)
BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();
for (Map.Entry
smsReceiverParams.setParam(entry.getKey(),entry.getValue());
}
for(int i=0;i // 3.4 增加接收短信的号码 batchSmsAttributes.addSmsReceiver(phoneList.get(i), smsReceiverParams); } //batchSmsAttributes.addSmsReceiver("$YourReceiverPhoneNumber2", smsReceiverParams); messageAttributes.setBatchSmsAttributes(batchSmsAttributes); try { /** * Step 4. 发布SMS消息 */ TopicMessage ret = topic.publishMessage(msg, messageAttributes); /* System.out.println("MessageId: " + ret.getMessageId()); System.out.println("MessageMD5: " + ret.getMessageBodyMD5());*/ return true; } catch (ServiceException se) { System.out.println(se.getErrorCode() + se.getRequestId()); System.out.println(se.getMessage()); se.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; }finally { client.close(); } } } 另外,需要的几个jar,可以到阿里云官方文档下载。 阿里云的短信并不便宜,在此只是提供一种学习。