一、准备工作
首先要开通阿里云的短信服务,然后在控制台中找到短信服务。进入后就是以下界面。其中我们需要4个东西:accessKeyId、accessKeySecret、短信模板和短信签名。

获取AcessKey:
accessKeyId、accessKeySecret是阿里云API的密钥,阿里云许多产品都需要他们绑定,所以需要注意防护。进入AccessKey页面通过短信获取即可,第一次使用的话需要创建一个,如下图所示。

短信签名申请:
需要注意的是短信签名不需要自己添加【】、()、[]符号,签名发送会自带【】符号,避免重复。其余个人和企业账户规则可在申请规范中详细查看。如下图:

短信模板申请:
1、选择模板类型。
2、设置模板名称。
3、设置模板内容:最终短信会显示的内容,变量用${code}占用。
4、填写申请说明。
示例及模板预览如下图:


二、代码实现
引入阿里云短信SDK
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>3.7.1</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> <version>1.1.0</version> </dependency>
|
示例工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
public class AlySmsUtils {
static final String product = "Dysmsapi"; static final String domain = "dysmsapi.aliyuncs.com";
static final String accessKeyId = "********"; static final String accessKeySecret = "***********";
public static void smsToTest(String telephone, String code) throws ClientException { String templateCode = "SMS_123456789"; sendSms(telephone,code, templateCode); }
public static SendSmsResponse sendSms(String telephone, String code, String templateCode) throws ClientException { System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000");
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest(); request.setPhoneNumbers(telephone); request.setSignName("测试模板"); request.setTemplateCode(templateCode); request.setTemplateParam("{\"code\":\"" + code + "\"}");
request.setOutId("yourOutId");
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) { System.out.println("短信发送成功!"); } else { System.out.println("短信发送失败!"); } return sendSmsResponse; } }
|
使用测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public static void SmsCode() throws ClientException { String telephone = "12345678910"; String code = "666666"; String templateCode = "SMS_132695077";
AlySmsUtils.sendSms(telephone, code, templateCode); }
public static void main(String[] args) throws ClientException { SmsCode(); }
|