In application development, you may need to send verification codes, notifications, or promotional messages to users. For example, you can send a verification code when a user registers an account or a notification when an order status changes. This topic shows you how to integrate the Alibaba Cloud software development kit (SDK) to call the Short Message Service (SMS) API, providing a fast, secure, and reliable way to automate sending text messages.
Architecture
Calling the Short Message Service API involves your application, the Alibaba Cloud SDK, Resource Access Management (RAM), and Short Message Service.
The core logic of the process is as follows: A developer integrates the Alibaba Cloud SDK into an application. The developer uses RAM to assign access credentials with Short Message Service permissions to the application. The application uses the credentials to call the Short Message Service API and send a request. The Alibaba Cloud server-side authenticates the request and checks for compliance. After the request is approved, the message is sent to an SMS gateway. The carrier network then delivers the message to the user's mobile phone.
This topic uses the SendMessageToGlobe operation as an example to guide you through calling the Short Message Service API. You will learn how to:
If you are familiar with how to call an API, you can go to the API reference to call the required operation.
We recommend that you integrate the SDK to call the API. If you want to customize request encapsulation to call the API, see Request body and signature mechanism V3.
Preparations
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 for Short Message Service:
| |
| You can go to the RAM console, click a RAM user name to enter the product page, click the AccessKey tab, and view the AccessKey ID. | |
| The AccessKey secret cannot be viewed after it is created. If you do not have a local backup, create a new AccessKey pair. | |
Account balance/Package quota | Make sure that your account has a sufficient balance or package quota. You can view the package quota on the Package Statistics page or view the account balance on the Expenses and Costs page in the console. |
Configure credentials
Step 1: Create a RAM user and grant permissions
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.
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.
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_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETas the environment variable names.
Step 3: Steps to configure environment variables
Windows
On Windows, you can configure an environment variable through System Properties, Command Prompt (CMD), or PowerShell.
System Properties
Environment variables configured this way are permanent.
Administrative permissions are required to modify system 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 line for the environment variable to take effect.
On the Windows desktop, press
Win+Q. In the search box, search for Edit the system environment variables and click to open the System Properties window.In the System Properties window, click Environment Variables. In the System variables section, click New. Set Variable name to
ALIBABA_CLOUD_ACCESS_KEY_IDand Variable value to your AccessKey ID. Repeat the process to setALIBABA_CLOUD_ACCESS_KEY_SECRET.
Click OK in each of the three windows to close the system properties configuration page and complete the configuration.
Open a CMD or Windows PowerShell window and run the following commands to check whether the environment variables are configured.
CMD command:
echo %ALIBABA_CLOUD_ACCESS_KEY_ID% echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%Windows PowerShell command:
echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRET
CMD
Add a permanent environment variable
If you want the API key environment variable to be available in all new sessions for the current user, perform the following steps.
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"Open a new CMD window.
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
If you want 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_SECRETYou can run the following commands in the current session to check whether the environment variables are configured.
echo %ALIBABA_CLOUD_ACCESS_KEY_ID%
echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%PowerShell
Add a permanent environment variable
If you want the API key environment variable to be available in all new sessions for the current user, perform the following steps.
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)Open a new PowerShell window.
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
If you want 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"You can 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_SECRETLinux
Add a permanent environment variable
If you want the API key environment variable to be available in all new sessions for the current user, add a permanent environment variable.
Run the following command to append the environment variable setting to the
~/.bashrcfile.# 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'" >> ~/.bashrcYou can also manually edit the
~/.bashrcfile.Run the following command to apply the changes.
source ~/.bashrcOpen a new terminal window and run the following commands to check whether the environment variables are configured. We recommend that you 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
If you want to use the environment variable only in the current session, add a temporary environment variable.
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"Run the following command to verify that the environment variable is configured.
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
macOS
Add a permanent environment variable
If you want the API key environment variable to be available in all new sessions for the current user, add a permanent environment variable.
Run the following command in the terminal to check the default shell type.
echo $SHELLPerform the following steps based on the default shell type.
Zsh
Run the following command to append the environment variable setting to the
~/.zshrcfile.# 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'" >> ~/.zshrcYou can also manually edit the
~/.zshrcfile.Run the following command to apply the changes.
source ~/.zshrcOpen 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
Run the following command to append the environment variable setting to the
~/.bash_profilefile.# 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_profileYou can also manually edit the
~/.bash_profilefile.Run the following command to apply the changes.
source ~/.bash_profileOpen 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
If you want to use the environment variable only in the current session, add a temporary environment variable.
The following commands apply to both Zsh and Bash.
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"Run the following command to verify that the environment variable is configured.
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
After you modify system environment variables, restart or refresh your development environment. This includes IDEs, command-line interfaces, 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.
Make sure that Java 8 or a later version is installed.
You can install the SDK by configuring a Maven dependency. Configure the following information and replace
the-latest-versionwith 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>
Use the SDK
1. Initialize the client
The Alibaba Cloud SDK supports various access credentials to initialize the client, such as an AccessKey pair and a Security Token Service (STS) token. For more information, 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 that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the 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 the runtime environment.
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// The System.getenv() method retrieves a system environment variable. Do not hardcode your AccessKey information in the getenv() method.
// 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 as needed.
The request object follows the naming convention of {API operation name}Request. For example, the request object for the SendMessageToGlobe operation is SendMessageToGlobeRequest.
SendMessageToGlobeRequest sendSmsRequest = new SendMessageToGlobeRequest()
.setTo("<YOUR_VALUE>")
.setMessage("<YOUR_VALUE>");3. Send the request
Use the SendMessageToGlobe operation to complete the API request.
The response object follows the naming convention of {API operation name}Response. For example, the response object for the SendMessageToGlobe operation is SendMessageToGlobeResponse.
SendMessageToGlobeResponse sendSmsResponse = client.sendMessageToGlobe(sendSmsRequest);You can also configure request parameters. For more information, see Initiate a request.
For information about timeout and retry settings, see Timeout mechanism and Retry mechanism.
For information about SDK exception types and how to handle them, see Exception handling.
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
Cost composition: Short Message Service is primarily billed based on the number of messages sent. The price per message varies by country or region. For detailed pricing, see Product 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 more information, see Solutions for AccessKey pair leaks.
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 content
To perform online debugging in the OpenAPI Portal, visit the OpenAPI Explorer for Short Message Service.
To send text messages in batches, use the BatchSendMessageToGlobe operation.
To learn about other scenarios of Short Message Service, see SDK Examples.
To obtain SMS statistics, such as message volume, visit or Business Statistics.

