Java SDK

Updated at:

The Alibaba Cloud SMS SDK for Java simplifies calling SMS API operations from Java applications. The SDK supports sending messages, managing signatures and templates, querying send records, and managing qualifications.

Installation

System requirements

Install with Maven

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>dysmsapi20170525</artifactId>
  <!-- Replace 'the-latest-version' with the latest version number: https://mvnrepository.com/artifact/com.aliyun/dysmsapi20170525 -->
  <version>the-latest-version</version>
</dependency>

Configure authentication

Step 1: Create a RAM user and grant permissions

Important

Your root account has full permissions. Use a RAM user for API calls and routine O&M. For more information, see Overview.

  • 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.

Note
  • AliyunDysmsFullAccess: Grants full permissions to manage the SMS service.

  • AliyunDysmsReadOnlyAccess: Grants read-only permissions to access the SMS service.

  • To create a custom policy, see RAM authorization.

Step 2: Configure access credentials

Store your AccessKey pair in environment variables. Configure environment variables on Linux, macOS, and Windows.

Note
  • Do not hard-code your AccessKey pair. Retrieve it from environment variables.

  • The sample code uses the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.

Step 3: Configure environment variables

Environment variables prevent hard-coded secrets in your source code.

Set the environment variables:

export ALIBABA_CLOUD_ACCESS_KEY_ID='your_access_key_id'
export ALIBABA_CLOUD_ACCESS_KEY_SECRET='your_access_key_secret'

Use in code:

import com.aliyun.tearpc.models.Config;
import com.aliyun.dysmsapi20170525.Client;

// The default credential chain automatically reads the environment variables.
Config config = new Config();
config.credential = new com.aliyun.credentials.Client(null);
config.endpoint = "https://dysmsapi.aliyuncs.com";
config.regionId = "cn-hangzhou";

Client client = new Client(config);

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 example calls the SMS API to send a message. Replace placeholder values as indicated in the comments.

package com.aliyun.sample;

import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
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.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.
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers("1390000****")
                .setSignName("Alibaba Cloud")
                .setTemplateCode("SMS_15305****")
                .setTemplateParam("{\"name\":\"Bob\",\"number\":\"1390000****\"}");

        // Obtain the response object.
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

        // The response includes the body and headers from the server.
        System.out.println(toJSONString(sendSmsResponse));
    }
}

Download the sample code

Download and run the sample code directly.

  1. Go to SendSms.

  2. On the Parameters tab, specify the required parameters. Example values:

  • PhoneNumbers: 139****0000

  • SignName: Alibaba Cloud Test

  • TemplateCode: SMS_15495****

  • TemplateParams: {"code":"1234"}

  1. 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.

  2. Extract the package, open the project in your IDE, wait for dependencies to load, and open src/main/java/com/aliyun/sample/Sample.java.

Run the project

Run the project. Sample response:

{
  "headers": {
    "access-control-allow-origin": "*",
    "date": "Mon, 17 Jul 2023 16:21:50 GMT",
    "content-length": "110",
    "keep-alive": "timeout=25",
    "x-acs-request-id": "F59B3F78-D9CD-5D01-A9CC-AE5C921ED9C0",
    "connection": "keep-alive",
    "content-type": "application/json;charset=utf-8",
    "etag": "1MzEw7RSXKXTkIJ1thYGmCw0",
    "access-control-expose-headers": "*",
    "x-acs-trace-id": "5ecfe30b412fb6e09a86d651ccbe13db"
  },
  "statusCode": 200,
  "body": {
    "bizId": "695425589610909881^0",
    "code": "OK",
    "message": "OK",
    "requestId": "F59B3F78-D9CD-5D01-A9CC-AE5C921ED9C0"
  }
}

Best practices

Performance optimization

  • Reuse HTTP connections with a connection pool to reduce overhead.

  • Use asynchronous calls for high-frequency scenarios.

  • Set timeouts to avoid blocking your service.

  • Use the built-in batch processing for bulk operations.

Security recommendations

  • Always use HTTPS to communicate with the API.

  • Do not log sensitive data such as mobile numbers or verification codes.

  • Validate user-entered mobile numbers to prevent malicious input.

  • Prefer temporary credentials from Alibaba Cloud Security Token Service (STS) over long-term credentials.

Resource management

  • Close unused client connections.

  • Size your thread pool to match expected concurrency.

  • Monitor API call frequency to avoid exceeding QPS limits.

FAQ

References

Video Tutorial