首先将短信签名和模板弄好
创建Access Key
- 登录阿里云账号
- 打开“我的Access Key”页面,页面地址:https://ak-console.aliyun.com/#/accesskey/
- 创建Access Key
(注:也可以使用阿里云访问控制服务创建的Access Key)
安装Java SDK
- 直接下载http://aliyundm.oss-cn-hangzhou.aliyuncs.com/example/aliyun-java-sdk-smsV1.zip
- eclipse中 build path 当中的两个jar包
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.sms.model.v20160927.SingleSendSmsRequest;
import com.aliyuncs.sms.model.v20160927.SingleSendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
public class SendSms {
public static void main(String[] args){
SendSms.sample();
}
public static void sample() {
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", "your accessKey", "your accessSecret");
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Sms", "sms.aliyuncs.com");
IAcsClient client = new DefaultAcsClient(profile);
SingleSendSmsRequest request = new SingleSendSmsRequest();
try {
request.setSignName("控制台创建的签名名称");
request.setTemplateCode("控制台创建的模板CODE");
request.setParamString("{}");//给模板中的变量赋值
request.setRecNum("接收号码");
SingleSendSmsResponse httpResponse = client.getAcsResponse(request);
} catch (ServerException e) {
e.printStackTrace();
}
catch (ClientException e) {
e.printStackTrace();
}
}
}