All Products
Search
Document Center

Short Message Service:Make your first API call

Last Updated:Feb 11, 2026

In application development, you may need to send text messages to users for verification codes, notifications, or promotional campaigns. For example, you can send a verification code for user registration or a notification for an order status update. This topic describes how to use the Alibaba Cloud software development kit (SDK) to quickly and securely call the Short Message Service API for automatic message delivery.

Solution architecture

Calling the Short Message Service API involves your application, the Alibaba Cloud SDK, Resource Access Management (RAM), and Short Message Service.

The process is as follows: A developer integrates the Alibaba Cloud SDK into an application and uses RAM to assign access credentials with Short Message Service permissions to the application. The application uses these credentials to call the Short Message Service API and send a request. After the Alibaba Cloud server-side authenticates the request and verifies compliance, the message is sent to the SMS gateway. The carrier then delivers the text message to the user's mobile phone.

image

This topic describes how to call the Short Message Service API using the and SendMessageToGlobe APIs as examples. You will learn how to perform the following tasks:

Note

Before you begin

Prerequisites

Description

References

User permissions

Go to the RAM console and click a RAM user name to view the user permissions. Make sure the RAM user that you use to call the API has the required permissions on Short Message Service:

  • AliyunDysmsFullAccess: Grants full permissions to manage Short Message Service.

Create and authorize a RAM user

Custom authorization information

AccessKey ID

Go to the RAM console, click a RAM user name, and then click the AccessKey tab to view the AccessKey ID.

Create and authorize a RAM user

AccessKey Secret

You cannot view the AccessKey secret after it is created. If you do not have a local backup, create a new AccessKey pair.

Account balance/Package quota

Ensure sufficient account balance or package quota. You can check package quotas on the Resource Package Statistics page or account balance in the Expenses and Costs console.

Billing

Configure credentials

Step 1: Create a RAM user and grant permissions

Important

Your Alibaba Cloud account has high-level permissions. For security, we recommend that you use a Resource Access Management (RAM) user for API calls and daily operations. For more information about RAM users, see Overview of RAM users.

  • Create a RAM user: Go to Create User. Configure the user name and set Access Configuration to Permanent AccessKey. Click OK. Save the AccessKey pair immediately after creation.

  • Grant permissions to the RAM user: Go to Users. Find the RAM user that you created and click Actions, then click Attach Policy. In the Policy search box, enter AliyunDysmsFullAccess, select the policy, and click OK.

Note
  • AliyunDysmsFullAccess: Grants full management permissions for Alibaba Cloud SMS.

  • AliyunDysmsReadOnlyAccess: Grants read-only permissions for Alibaba Cloud SMS.

  • To create a custom policy, see RAM authorization.

Step 2: Get your access credentials

Configure environment variables to store your AccessKey pair. For more information, see Configure environment variables in Linux, macOS, and Windows.

Note
  • To avoid leaking your AccessKey pair, do not hard-code it in your application. Use environment variables instead.

  • This example uses ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as the environment variable names.

Step 3: Configure environment variables

Windows

On Windows, you can configure environment variables using System Properties, Command Prompt (CMD), or PowerShell.

System Properties

Note
  1. Environment variables that are configured using this method are permanent.

  2. Administrative permissions are required to modify system environment variables.

  3. After you configure an environment variable, it does not immediately take effect in open command windows, IDEs, or other running applications. You must restart these programs or open a new command prompt for the change to take effect.

  1. On the Windows desktop, press Win+Q. In the search box, enter Edit the system environment variables and click the result to open the System Properties window.

  2. In the System Properties window, click Environment Variables. In the System variables section, click New. Enter ALIBABA_CLOUD_ACCESS_KEY_ID for Variable name and your AccessKey ID for Variable value. Repeat this step to set the ALIBABA_CLOUD_ACCESS_KEY_SECRET variable.

    image

  3. Click OK in each of the three open windows to save the configuration and close the windows.

  4. Open a Command Prompt (CMD) or Windows PowerShell window and run the following commands to check whether the environment variables are configured.

    1. CMD query command:

      echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
      echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

    2. Windows PowerShell query command:

      echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET

CMD

Add a permanent environment variable

To make the AccessKey pair environment variables available in all new sessions for the current user, perform the following steps.

  1. Run the following commands in CMD:

    # Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
    setx ALIBABA_CLOUD_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    # Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
    setx ALIBABA_CLOUD_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. Open a new CMD window.

  3. Run the following commands in the new CMD window to check whether the environment variables are configured.

    echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
    echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

Add a temporary environment variable

To use the environment variable only in the current session, you can run the following command in CMD.

# Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
set ALIBABA_CLOUD_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID
# Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
set ALIBABA_CLOUD_ACCESS_KEY_SECRET=YOUR_ACCESS_KEY_SECRET

You can run the following commands in the current session to verify that the environment variables are set correctly.

echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

PowerShell

Add a permanent environment variable

To make the AccessKey pair environment variables available in all new sessions for the current user, perform the following steps.

  1. Run the following commands in PowerShell:

    # Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
    [Environment]::SetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
    # Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
    [Environment]::SetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Open a new PowerShell window.

  3. Run the following commands in the new PowerShell window to check whether the environment variables are configured.

    echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET

Add a temporary environment variable

To use the environment variables only in the current session, run the following commands in PowerShell.

# Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
$env:ALIBABA_CLOUD_ACCESS_KEY_ID = "YOUR_ACCESS_KEY_ID"
# Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
$env:ALIBABA_CLOUD_ACCESS_KEY_SECRET = "YOUR_ACCESS_KEY_SECRET"

Run the following commands in the current session to check whether the environment variables are configured.

echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET

Linux

Add a permanent environment variable

To make the AccessKey pair environment variables available in all new sessions for the current user, configure permanent environment variables.

  1. Run the following command to append the environment variable settings to the ~/.bashrc file.

    # Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
    echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    # Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
    echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc

    You can also manually edit the ~/.bashrc file.

    Manual modification

    Run the following command to open the ~/.bashrc file.

    nano ~/.bashrc

    Add the following content to the configuration file.

    # Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
    export ALIBABA_CLOUD_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
    # Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET="YOUR_ACCESS_KEY_SECRET"

    In the nano editor, press Ctrl + X, then Y, and then Enter to save and close the file.

  2. Run the following command to apply the changes.

    source ~/.bashrc
  3. Open a new terminal window and run the following commands to check whether the environment variables are configured. Restart your IDE before you use the SDK.

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

Add a temporary environment variable

To use the environment variables only in the current session, add a temporary environment variable.

  1. Run the following commands.

    # Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
    export ALIBABA_CLOUD_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
    # Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET="YOUR_ACCESS_KEY_SECRET"
  2. Run the following commands to verify that the environment variables are configured.

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

macOS

Add a permanent environment variable

To make the AccessKey pair environment variables available in all new sessions for the current user, configure permanent environment variables.

  1. Run the following command in the terminal to check the default shell type.

    echo $SHELL
  2. Perform the following operations based on the default shell type.

    Zsh

    1. Run the following command to append the environment variable settings to the ~/.zshrc file.

      # Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
      echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
      # Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
      echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc

      You can also manually edit the ~/.zshrc file.

      Manual modification

      Run the following command to open the shell configuration file.

      nano ~/.zshrc

      Add the following content to the configuration file.

      # Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
      export ALIBABA_CLOUD_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
      # Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET="YOUR_ACCESS_KEY_SECRET"

      In the nano editor, press Ctrl + X, then Y, and then Enter to save and close the file.

    2. Run the following command to apply the changes.

      source ~/.zshrc
    3. Open a new terminal window and run the following commands to check whether the environment variables are configured.

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

    Bash

    1. Run the following command to append the environment variable settings to the ~/.bash_profile file.

      # Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
      echo "export ALIBABA_CLOUD_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
      # Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
      echo "export ALIBABA_CLOUD_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile

      You can also manually edit the ~/.bash_profile file.

      Manual modification

      Run the following command to open the shell configuration file.

      nano ~/.bash_profile

      Add the following content to the configuration file.

      # Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
      export ALIBABA_CLOUD_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
      # Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET="YOUR_ACCESS_KEY_SECRET"

      In the nano editor, press Ctrl + X, then Y, and then Enter to save and close the file.

    2. Run the following command to apply the changes.

      source ~/.bash_profile
    3. Open a new terminal window and run the following commands to check whether the environment variables are configured.

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

Add a temporary environment variable

To use the environment variables only in the current session, add a temporary environment variable.

The following commands apply to both Zsh and Bash.
  1. Run the following commands.

    # Replace YOUR_ACCESS_KEY_ID with your AccessKey ID
    export ALIBABA_CLOUD_ACCESS_KEY_ID="YOUR_ACCESS_KEY_ID"
    # Replace YOUR_ACCESS_KEY_SECRET with your AccessKey secret
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET="YOUR_ACCESS_KEY_SECRET"
  2. Run the following commands to verify that the environment variables are configured.

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

After you modify the system environment variables, you must restart or refresh your compilation and runtime environment. This includes your IDE, command-line interface, other desktop applications, and background services. This ensures that the latest system environment variables are loaded.

Install the SDK

This topic uses Java as an example. If you use a different programming language, see SDK reference.

  1. Java 8 or later is installed.

    Configure the Java environment

    Check your Java environment by running the following command in your terminal:

    java -version
    # If you use Maven to manage and build your Java projects, ensure Maven is correctly installed in your development environment.
    mvn --version

    For example, you can use the Windows Command Prompt.

    image

    The Short Message Service SDK requires Java 8 or a later version. You can check your Java version in the first line of the output. For example, openjdk version "16.0.1" 2021-04-20 indicates that the Java version is 16. If Java is not installed or the version is earlier than 8, go to Java Downloads to download and install it.

  2. Install the SDK by configuring a Maven dependency. Replace the-latest-version with the latest version number.

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

    Maven configuration

    1. Open the pom.xml file of your Maven project.

    2. Add the preceding dependency information within the <dependencies> tag.

    3. Save the pom.xml file.

    4. Right-click the project name and select Maven > Reload project to update the dependencies. Maven automatically downloads and adds the Short Message Service SDK to your project.

      image

Use the SDK

1. Initialize the client

The Alibaba Cloud SDK supports various types of access credentials for client initialization, such as an AccessKey pair and a Security Token Service (STS) token. For more information about initialization methods, see Manage access credentials. This topic uses an AccessKey pair to initialize the client as an example.

package com.aliyun.sample;

import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20180501.Client;

public class Sample {
    public static Client createClient() throws Exception {
        Config config = new Config()
                // Configure the AccessKey ID. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Configure the AccessKey secret. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
                // The System.getenv() method retrieves system environment variables. Do not hardcode your AccessKey information.
        
        // Configure the endpoint.
        config.endpoint = "dysmsapi.ap-southeast-1.aliyuncs.com";

        return new Client(config);
    }
}

2. Build the request object

Construct the API request and pass the required parameters.

Note

The request object is named in the format: {API-Name}Request. For example, the request object for the SendMessageToGlobe API is SendMessageToGlobeRequest.

SendMessageToGlobeRequest sendSmsRequest = new SendMessageToGlobeRequest()
            .setTo("<YOUR_VALUE>")
            .setMessage("<YOUR_VALUE>");

3. Send the request

Use the SendMessageToGlobe operation to send the API request.

Note

The response object is named in the format: {API-Name}Response. For example, the response object for the SendMessageToGlobe API is SendMessageToGlobeResponse.

SendMessageToGlobeResponse sendSmsResponse = client.sendMessageToGlobe(sendSmsRequest);

Code example

The following code provides a complete example:

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 the AccessKey ID. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Configure the AccessKey secret. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in runtime environment.
                .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();

        // Construct the request object. Enter the request parameter values.
        SendMessageToGlobeRequest sendSmsRequest = new SendMessageToGlobeRequest()
                .setTo("<YOUR_VALUE>")
                .setMessage("<YOUR_VALUE>");

        // Get the response object.
        SendMessageToGlobeResponse sendSmsResponse = client.sendMessageToGlobe(sendSmsRequest);

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

After you run the code, the following output is returned:

{
  "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"
  }
}

API error codes and solutions

For more information, see Error codes.

Costs and risks

  • Costs: SMS is primarily billed based on the number of messages sent. The price per message varies by country or region. For more information about pricing, see Billing, , and .

  • Key risks:

    • Credential leaks: If your AccessKey pair is leaked, all resources under your account are compromised. This can result in unauthorized resource usage, unexpected charges, and data security breaches. In critical cases, this can even harm Alibaba Cloud or other users. For more information, see Remediate potentially compromised AccessKey pairs.

    • Content compliance: The content that you send must comply with the laws and regulations of the destination country or region. Otherwise, the message may fail to be sent, or your account may be suspended.

Related Topics