All Products
Search
Document Center

Short Message Service:Get started with SMS API

Last Updated:Oct 18, 2025

In application development, you may need to send verification codes, notifications, or promotional campaigns to users via mobile messages. For example, send a verification code for user registration or a notification for order status updates. This topic demonstrates how to leverage Alibaba Cloud SDK to quickly and securely call the Short Message Service (SMS) API for automatic message delivery.

Architecture

Sending a message involves secure interaction between your application, the Alibaba Cloud SDK, Resource Access Management (RAM), and SMS.

This process begins when a developer integrates the Alibaba Cloud SDK into their application. To ensure security, RAM is used to grant the application the necessary permissions to access the SMS service via a set of credentials. With these credentials, the application can initiate a call to the SMS API. Alibaba Cloud server authenticates the request and, upon approval, forwards the message to an SMS gateway for delivery to the user's device via carrier networks.

image

This guide walks you through the process of calling the SMS API, using SendMessageToGlobe as an example. You will learn how to:

Note

Before you begin

Item

Description

References

User permissions

Check user permissions by clicking a RAM user name in the RAM console. Ensure the RAM user that you use to call the API has the necessary SMS permissions:

  • AliyunDysmsFullAccess: Grants full permissions to manage SMS resources.

Create and authorize a RAM user

RAM authorization

AccessKey ID

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

Create a RAM user and an AccessKey pair

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

  1. Create a RAM user with permissions to manage SMS resources, then create an AccessKey pair.

    Note

    For security, use RAM users for API calls and daily operations instead of your Alibaba Cloud account.

    Create and authorize a RAM user

    1. Create a RAM user and an AccessKey pair

      Go to the Create User page, set the user information, select Using permanent AccessKey to access for Access Mode, and click OK. After you pass the security verification, the RAM user is created. The system displays the AccessKey ID and AccessKey Secret. Save them securely.

    2. Grant permissions to the RAM user

      Go to the Users page, find the RAM user you created, and click Add Permissions in the Actions column. Search for and select AliyunDysmsFullAccess, and then click Grant permissions to complete the authorization.

  2. Configure environment variables with the RAM user's AccessKey pair. This topic uses the environment variable names ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as examples.

    Note

    To prevent security risks from hardcoded credentials, use environment variables to store your AccessKey pair.

    Configure environment variables

    Windows

    On Windows, you can configure an environment variable through System Properties, Command Prompt (CMD), or PowerShell.

    System Properties

    Note
    • Environment variables configured this way are permanent.

    • Administrator privileges are required to modify system-wide environment variables.

    • Configuring an environment variable does not immediately affect open command windows, IDEs, or other running applications. You must restart these programs or open a new command prompt for the environment variable to take effect.

    1. On the Windows desktop, press Win+Q, search for Edit the system environment variables, and click 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 the Variable name and your AccessKey ID for the Variable value. Repeat the process to set ALIBABA_CLOUD_ACCESS_KEY_SECRET.

      image

    3. Click OK in each of the three windows to close the system properties configuration page. The environment variables are configured.

    4. Open a CMD or PowerShell window and run the following commands to check if the environment variables are set correctly.

      • CMD:

        echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
        echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

      • PowerShell:

        echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
        echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET

    CMD

    Add a permanent environment variable

    To make the API key environment variable available in all new sessions for the current user, follow these 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 to check if the environment variables are set correctly.

      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, run the following commands 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

    Run the following commands in the current session to check if 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 API key environment variable available in all new sessions for the current user, follow these 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 if the environment variables are set correctly.

      echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET

    Add a temporary environment variable

    To use the environment variable 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 if the environment variables are set correctly.

    echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET

    Linux

    Add a permanent environment variable

    To make the API key environment variable available in all new sessions for the current user, add a permanent environment variable.

    1. Run the following command to append the environment variable setting 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 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 if the environment variables are set correctly. Restart your IDE and terminal sessions 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 variable 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 API key environment variable available in all new sessions for the current user, add a permanent environment variable.

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

      echo $SHELL
    2. Follow the steps based on your default shell type.

      Zsh

      1. Run the following command to append the environment variable setting 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 setting 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 variable 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
  3. After you modify system environment variables, restart your applications, including IDEs and terminal sessions, for the changes to take effect.

Install the SDK

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

  1. Ensure you have Java 8 or a later version 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

    Example for CMD on Windows:

    image

    You can check your Java version from the first line of the output. For example, openjdk version "16.0.1" 2021-04-20 indicates that the current Java version is 16. If your environment does not have Java or the version is below 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 dependency information above 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 SMS SDK to your project.

      image

Use the SDK

1. Initialize the client

The Alibaba Cloud SDK supports various types of credentials for client initialization. For more methods, see Manage access credentials. This topic uses an AccessKey pair to initialize the client.

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 parameters according to your business needs.

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 SendMessageToGlobe to complete 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 complete code example is as follows:

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 details, 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 detailed pricing, see Billing.

  • Key risks:

    • Credential leaks: An AccessKey pair leak compromises all resources under your account. This can result in unauthorized resource usage, unexpected charges, and data security breaches. For details, see Solutions to AccessKey pair leaks.

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

References