All Products
Search
Document Center

Short Message Service:Make your first API call

Last Updated:Jun 12, 2026

Application development often involves sending SMS to users for things like registration verification codes, order update notifications, or promotional messages. This document describes how to quickly, securely, and reliably automate SMS sending by integrating an SDK and calling the Alibaba Cloud Short Message Service API.

Architecture

The end-to-end flow of calling the SMS API involves your application, the Alibaba Cloud SDK, Resource Access Management (RAM), and SMS.

The process is as follows: You integrate the Alibaba Cloud SDK into your application and use RAM to assign credentials with SMS permissions to your application. Your application uses these credentials to call the SMS API. After Alibaba Cloud authenticates the request and verifies compliance, it passes the message to the Alibaba Cloud SMS Gateway, which then delivers the SMS to the user's mobile phone over the carrier network.

image

This guide shows you how to call the SMS API, using the SendMessageToGlobe operation as an example. You will learn how to:

Note
  • If you are familiar with calling APIs, you can refer directly to the API reference and call the operation you need.

  • We recommend using the SDK to call the API. If you prefer to build your own requests, see V3 request body & signature.

Before you begin

Item

Description

References

User permissions

In the RAM console, click a RAM user's name to view their permissions. Ensure that the RAM user calling the API has the required SMS-related permission:

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

Step 1: Create a RAM user and grant permissions

Custom authorization

AccessKey ID

In the RAM console, click a RAM user's name. On the user details page, click the AccessKey tab to view the AccessKey ID.

Step 1: Create a RAM user and grant permissions

AccessKey Secret

The AccessKey Secret is shown only at creation. If lost, create a new AccessKey pair.

Account balance or package quota

Ensure that you have a sufficient account balance or package quota. You can view your package quota on the Resource Package Statistics page or check your account balance in the Expenses and Costs console.

Billing

Configure credentials

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

Windows

On Windows, you can configure environment variables by using System Properties, CMD, or PowerShell.

System properties

Note
  1. This method sets permanent environment variables.

  2. Administrator privileges are required to modify system variables.

  3. Changes to environment variables do not affect running applications. You must restart any open command-line interfaces, IDEs, or other applications to apply the new variable settings.

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

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

  3. Click OK in all three windows to save the settings and close them.

  4. Open a CMD or Windows PowerShell window and run the following commands to verify that the environment variables are set.

    1. CMD command:

      echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
      echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%
      Microsoft Windows [Version 10.0.22621.3593]
      (c) Microsoft Corporation. All rights reserved.
      C:\Windows\System32>echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
      LTAI
      C:\Windows\System32>
    2. Windows PowerShell command:

      echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET
      Windows PowerShell
      Copyright (C) Microsoft Corporation. All rights reserved.
      Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows
      PS C:\Windows\system32> echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
      LTAIxxx
      PS C:\Windows\system32>

CMD

Permanent

To set an environment variable that persists across 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. In the new CMD window, run the following commands to verify that the environment variables are set.

    echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
    echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

Temporary

To set an environment variable for the current session only, 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

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

echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%

PowerShell

Permanent

To set an environment variable that persists across 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. In the new PowerShell window, run the following commands to verify that the environment variables are set.

    echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET

Temporary

To set an environment variable for the current session only, 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"

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

echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID
echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET

Linux

Permanent

To set an environment variable that persists across all new sessions for the current user, add the variable to your shell's startup file.

  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 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 to exit, Y to save the changes, and then Enter to confirm.

  2. Run the following command to apply the changes.

    source ~/.bashrc
  3. Reopen a terminal window and run the following commands to verify that the environment variables are set. Restart your IDE before you use the SDK.

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

Temporary

To set an environment variable for the current session only, follow these steps.

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

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

macOS

Permanent

To set an environment variable that persists across all new sessions for the current user, add the variable to your shell's startup file.

  1. Run the following command in a terminal to check your 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 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 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 to exit, Y to save the changes, and then Enter to confirm.

    2. Run the following command to apply the changes.

      source ~/.zshrc
    3. Reopen a terminal window and run the following commands to verify that the environment variables are set.

      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 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 to exit, Y to save the changes, and then Enter to confirm.

    2. Run the following command to apply the changes.

      source ~/.bash_profile
    3. Reopen a terminal window and run the following commands to verify that the environment variables are set.

      echo $ALIBABA_CLOUD_ACCESS_KEY_ID
      echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

Temporary

To set an environment variable for the current session only, follow these steps.

The following commands work for 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 set.

    echo $ALIBABA_CLOUD_ACCESS_KEY_ID
    echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET

After you modify environment variables, restart or refresh your build and runtime environment. This ensures that applications such as IDEs, command-line interfaces, and background services load the new variables.

Install the SDK

This guide provides examples for Java and Python. For other languages, see the SDK Reference. For complete usage instructions in Python, see Python SDK.

  1. Ensure that Java 8 or a later version is installed.

    Java environment

    Run the following commands in your terminal to check your Java environment:

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

    The following example shows the output in Windows CMD:

    C:\Users\Administrator>java --version
    java 23.0.2 2025-01-21
    Java(TM) SE Runtime Environment (build 23.0.2+7-58)
    Java HotSpot(TM) 64-Bit Server VM (build 23.0.2+7-58, mixed mode, sharing)
    C:\Users\Administrator>mvn --version
    Apache Maven 3.9.9 (8e8579a9e76f7d015ee5ec7bfcdc97d260186937)
    Maven home: C:\Program Files\apache-maven-3.9.9
    Java version: 23.0.2, vendor: Oracle Corporation, runtime: C:\Program Files\jdk-23.0.2
    Default locale: zh_CN, platform encoding: UTF-8
    OS name: "windows server 2022", version: "10.0", arch: "amd64", family: "windows"

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

  2. Install the SDK by adding the following 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 steps

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

    2. Add the dependency to the <dependencies> section.

    3. Save the pom.xml file.

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

If you use Python, install the SDK using pip. Ensure that Python 3.7 or a later version is installed.

pip install alibabacloud_dysmsapi20180501

Use the SDK

1. Initialize the client

The Alibaba Cloud SDK supports initializing the client with various credentials, such as an AccessKey or an STS Token. For more information, see Manage credentials. This topic uses an AccessKey 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 that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Configure the AccessKey secret. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
                // The System.getenv() method retrieves a system environment variable. Do not hard-code your AccessKey credentials in the code.
        
        // Configure the endpoint.
        config.endpoint = "dysmsapi.ap-southeast-1.aliyuncs.com";

        return new Client(config);
    }
}

2. Build the request object

Create the API request and set the parameters based on your requirements.

Note

Request object naming convention: {APIName}Request, for example, the request object for the SendMessageToGlobe API is SendMessageToGlobeRequest.

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

3. Initiate the request

Use the SendMessageToGlobe API to initiate an API request.

Note

Response object naming convention: {API name}Response. For example, the response object for the SendMessageToGlobe API is SendMessageToGlobeResponse.

SendMessageToGlobeResponse sendSmsResponse = client.sendMessageToGlobe(sendSmsRequest);

Code 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 that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Configure the AccessKey secret. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your 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 client.
        Client client = Sample.createClient();

        // Construct the request object. Replace the parameter values with your actual 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));
    }
}

Python code example

import os
from alibabacloud_dysmsapi20180501.client import Client
from alibabacloud_tea_openapi.models import Config
from alibabacloud_dysmsapi20180501.models import SendMessageToGlobeRequest

def create_client():
    config = Config(
        # Configure the AccessKey ID. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
        access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        # Configure the AccessKey secret. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
        access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    )
    # Configure the endpoint.
    config.endpoint = 'dysmsapi.ap-southeast-1.aliyuncs.com'
    return Client(config)

if __name__ == '__main__':
    # Initialize the client.
    client = create_client()
    # Construct the request object. Replace the parameter values with your actual values.
    request = SendMessageToGlobeRequest(
        to='<YOUR_VALUE>',
        message='<YOUR_VALUE>'
    )
    # Get the response object.
    response = client.send_message_to_globe(request)
    # The response includes the body from the server.
    print(response.body)

The output is similar to the following:

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

For more information, see Error codes for international messages.

Costs and risks

  • Cost breakdown: SMS is billed per message, and the price varies by country or region. For detailed pricing, see billing.

  • Key risks:

    • Credential leaks: A leaked AccessKey can compromise all resources in your account, leading to unexpected charges or extortion. In severe cases, its misuse can also harm Alibaba Cloud or other users. For details, see Handle leaked AccessKeys.

    • Content compliance: You must ensure that sent content complies with the laws and regulations of the destination country or region. Failure to comply can result in blocked messages or account suspension.

Related content