springboot调用阿里云发送国际短信代码实现
时间: 2023-10-19 07:00:48 浏览: 251
首先,你需要在阿里云短信控制台中创建签名和模板,并获取到 AccessKeyId 和 AccessKeySecret。
接下来,在Spring Boot项目中添加阿里云 Java SDK的依赖:
```
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.0.0</version>
</dependency>
```
然后,在项目的 application.properties 文件中添加阿里云短信服务的相关配置:
```
aliyun.sms.accessKeyId=yourAccessKeyId
aliyun.sms.accessKeySecret=yourAccessKeySecret
aliyun.sms.signName=yourSignName
aliyun.sms.templateCode=yourTemplateCode
```
在代码中,你可以使用以下示例代码发送国际短信:
```java
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sms.model.v20170628.SendSmsRequest;
import com.aliyuncs.sms.model.v20170628.SendSmsResponse;
import java.util.Arrays;
public class SmsUtil {
private String accessKeyId;
private String accessKeySecret;
private String signName;
private String templateCode;
public SmsUtil(String accessKeyId, String accessKeySecret, String signName, String templateCode) {
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.signName = signName;
this.templateCode = templateCode;
}
public boolean sendSms(String phoneNumber, String message) {
IClientProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("default", "default", "Dysmsapi", "dysmsapi.aliyuncs.com");
IAcsClient client = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(phoneNumber);
request.setSignName(signName);
request.setTemplateCode(templateCode);
request.setTemplateParam("{\"code\":\"" + message + "\"}");
try {
SendSmsResponse response = client.getAcsResponse(request);
if (response.getCode() != null && response.getCode().equals("OK")) {
return true;
}
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
// 使用示例
SmsUtil smsUtil = new SmsUtil(
"yourAccessKeyId",
"yourAccessKeySecret",
"yourSignName",
"yourTemplateCode"
);
boolean result = smsUtil.sendSms("+86xxxxxxxxxxx", "yourMessage");
System.out.println(result);
}
}
```
其中,phoneNumber 是接收短信的手机号码,message 是短信内容,可以根据模板中定义的变量替换。调用 sendSms 方法即可发送短信。
阅读全文