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.
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:
If you are familiar with API calls, you can directly use the API reference to call the required operations.
We recommend that you call API operations using SDKs. If you prefer to construct your own API requests, see Request syntax and signature method V3.
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:
| |
| Go to the RAM console, click a RAM user name, and then click the AccessKey tab to view the AccessKey ID. | |
| 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. |
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: Configure environment variables
Windows
On Windows, you can configure environment variables using System Properties, Command Prompt (CMD), or PowerShell.
System Properties
Environment variables that are configured using this method are permanent.
Administrative permissions are required to modify system environment variables.
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.
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.In the System Properties window, click Environment Variables. In the System variables section, click New. Enter
ALIBABA_CLOUD_ACCESS_KEY_IDfor Variable name and your AccessKey ID for Variable value. Repeat this step to set theALIBABA_CLOUD_ACCESS_KEY_SECRETvariable.
Click OK in each of the three open windows to save the configuration and close the windows.
Open a Command Prompt (CMD) or Windows PowerShell window and run the following commands to check whether the environment variables are configured.
CMD query command:
echo %ALIBABA_CLOUD_ACCESS_KEY_ID% echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%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.
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
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_SECRETYou 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.
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
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_SECRETLinux
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.
Run the following command to append the environment variable settings 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. 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.
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 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.
Run the following command in the terminal to check the default shell type.
echo $SHELLPerform the following operations based on the default shell type.
Zsh
Run the following command to append the environment variable settings 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 settings 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
To use the environment variables 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 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.
Java 8 or later is installed.
Install the SDK by configuring a Maven dependency. 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 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.
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.
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);You can also configure request parameters. For more information, see Initiate an API request.
For more information about timeout and retry settings, see Configure a timeout period and Configure a retry mechanism.
For more 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
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
To perform online debugging in the OpenAPI portal, visit OpenAPI Explorer.
To send text messages in batches, you can use the BatchSendMessageToGlobe operation.
For more SMS use cases, see SDK examples.
To obtain statistical data, such as the volume of sent messages, go to the Dashboard page.

