The official Alibaba Cloud SMS SDK for Java helps developers quickly integrate SMS capabilities into their applications by simplifying the process of calling Alibaba Cloud SMS API.
Installation
System requirements
Java version: Requires Java 8 or later. To set up a Java development environment, see Set up a Java development environment on Windows.
Operating system: Windows, Linux, or macOS.
Other dependencies: Maven 3.0 or later for project builds.
Install with Maven
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20180501</artifactId>
<!-- Replace 'the-latest-version' with the latest version number: https://mvnrepository.com/artifact/com.aliyun/dysmsapi20180501 -->
<version>the-latest-version</version>
</dependency>Configure authentication
Step 1: Create a RAM user and grant permissions
Because your root account has high privileges, we recommend using a RAM user for API calls and routine O&M. For more information, see Overview of RAM users.
Create a RAM user: Go to the Create User page. Specify the required information, select Permanent AccessKey for Access Configuration, then click OK. Save your AccessKey for later use.
Grant permissions to the RAM User: Go to the Users page. Find the RAM user that you created and click Attach Policy in the Actions column. In the Policy search box, enter AliyunDysmsFullAccess, select the policy, and then click OK.
AliyunDysmsFullAccess: Grants full permissions to manage the SMS service.
AliyunDysmsReadOnlyAccess: Grants read-only permissions to access the SMS service.
If you need to create a custom policy, see RAM authorization.
Step 2: Obtain access credentials
Configure your AccessKey pair using environment variables. For information about how to configure environment variables, see Configure environment variables on Linux, macOS, and Windows.
To prevent security risks, avoid hard-coding your AccessKey pair. Instead, retrieve it from environment variables.
The sample code in this topic uses the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET.
Security best practices
Store credentials by using environment variables or a key management service.
Rotate your AccessKey pair on a regular basis.
Follow the principle of least privilege by granting the minimum required permissions to RAM Users.
Do not print credential information in logs.
Use a RAM Role instead of your root account credentials in production environments.
Quick start
Sample code
This sample code demonstrates how to call the SMS API to send messages. Replace the placeholder values as instructed in the code comments.
package com.aliyun.sample;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20180501.Client;
import com.aliyun.dysmsapi20180501.models.SendMessageToGlobeRequest;
import com.aliyun.dysmsapi20180501.models.SendMessageToGlobeResponse;
import static com.aliyun.teautil.Common.toJSONString;
public class Sample {
public static Client createClient() throws Exception {
Config config = new Config()
// Configure your AccessKey ID. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// Configure your AccessKey secret. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Configure the endpoint.
config.endpoint = "dysmsapi.ap-southeast-1.aliyuncs.com";
return new Client(config);
}
public static void main(String[] args) throws Exception {
// Initialize the request client.
Client client = Sample.createClient();
// Create a request object and specify the parameter values.
SendMessageToGlobeRequest sendSmsRequest = new SendMessageToGlobeRequest()
.setTo("<YOUR_VALUE>")
.setMessage("<YOUR_VALUE>");
// Obtain the response object.
SendMessageToGlobeResponse sendSmsResponse = client.sendMessageToGlobe(sendSmsRequest);
// The response includes the body and headers from the server.
System.out.println(toJSONString(sendSmsResponse));
}
}Download the sample code
You can also download the sample code and run it directly.
Go to SendMessageToGlobe.
On the Parameters tab on the left, specify the required parameters. The following are example values:
To: 88691567****
Message: This is a test message.
On the SDK Sample Code tab on the right, select V2.0 for the SDK version and select Java for the language (Java or Java asynchronous). Click Download Project to download the sample code package.
Unzip the package, load the project in your IDE, and wait for the dependencies to load. Open
src/main/java/com/aliyun/sample/Sample.java.
Run the project
Run the project to view the output. A sample response is as follows:
{
"headers": {
"date": "Tue, 24 Oct 2023 07:47:17 GMT",
"content-type": "application/json;charset=utf-8",
"content-length": "263",
"connection": "keep-alive",
"keep-alive": "timeout=25",
"access-control-allow-origin": "*",
"access-control-expose-headers": "*",
"x-acs-request-id": "97B1D7B6-F2F6-3A50-97BC-A90B43EC962F",
"x-acs-trace-id": "29c11fe4c778b74774d5f5602f0e7975",
"etag": "2a+mcDRTDkXqx9VF7b6U57Q3"
},
"statusCode": 200,
"body": {
"ResponseCode": "OK",
"NumberDetail": {
"Region": "Taiwan",
"Country": "Taiwan, Province of China",
"Carrier": "FarEasTone"
},
"RequestId": "97B1D7B6-F2F6-3A50-97BC-A90B43EC962F",
"Segments": "1",
"ResponseDescription": "OK",
"To": "88691567****",
"MessageId": "191921698133637273"
}
}Best practices
Performance optimization
Use a connection pool to reuse HTTP connections and reduce connection setup overhead.
For high-frequency calls, consider using an asynchronous call pattern.
Set an appropriate timeout to prevent long waits from affecting service performance.
For batch operations, use the API's built-in batch processing capabilities.
Security recommendations
Always use HTTPS to communicate with the API.
Do not include sensitive information, such as mobile numbers and verification codes, in logs.
Verify the format of mobile numbers entered by users to prevent malicious input.
Prefer temporary credentials from Alibaba Cloud Security Token Service (STS) over long-term credentials.
Resource management
Close unused client connections.
For a large number of concurrent requests, configure an appropriate thread pool size.
Monitor API call frequency to avoid exceeding QPS limits.
References
GitHub repositories:
API reference:
Before you call an OpenAPI operation, we recommend that you read the related API reference, such as SendMessageToGlobe, to understand the required parameters, permissions, and other details. For more information, see API overview.
Call an API:
The SDK is the recommended way to call an API. This topic uses the Java SDK as an example. SDK usage in other languages is similar. For more information, see SMS SDK.