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.
This guide shows you how to call the SMS API, using the SendMessageToGlobe operation as an example. You will learn how to:
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:
| |
| In the RAM console, click a RAM user's name. On the user details page, click the AccessKey tab to view the AccessKey ID. | |
| 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. |
Configure credentials
Step 1: Create a RAM user and grant permissions
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.
-
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.
-
Do not hard-code your AccessKey pair. Retrieve it from environment variables.
-
The sample code uses the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_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
This method sets permanent environment variables.
Administrator privileges are required to modify system variables.
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.
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.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 this step forALIBABA_CLOUD_ACCESS_KEY_SECRET.Click OK in all three windows to save the settings and close them.
Open a CMD or Windows PowerShell window and run the following commands to verify that the environment variables are set.
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>Windows PowerShell command:
echo $env:ALIBABA_CLOUD_ACCESS_KEY_ID echo $env:ALIBABA_CLOUD_ACCESS_KEY_SECRETWindows 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.
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.
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_SECRETYou 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.
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.
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_SECRETLinux
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.
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 ~/.bashrcReopen 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.
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 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.
Run the following command in a terminal to check your default shell type.
echo $SHELLFollow the steps based on your 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 ~/.zshrcReopen 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
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_profileReopen 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.
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 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.
Ensure that Java 8 or a later version is installed.
Install the SDK by adding the following 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>
If you use Python, install the SDK using pip. Ensure that Python 3.7 or a later version is installed.
pip install alibabacloud_dysmsapi20180501Use 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.
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.
Response object naming convention: {API name}Response. For example, the response object for the SendMessageToGlobe API is SendMessageToGlobeResponse.
SendMessageToGlobeResponse sendSmsResponse = client.sendMessageToGlobe(sendSmsRequest);You can also configure other request parameters. For more information, see Initiate an API request.
For information about timeout and retry settings, see Configure a timeout period and Configure a retry mechanism.
For information about SDK exception types and their handling, see Exception handling.
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
Debug API calls in OpenAPI Explorer.
Use the BatchSendMessageToGlobe operation to send SMS messages in batches.
Find more Short Message Service use cases in SDK examples.
Refer to the Python SDK.
View message statistics on the dashboard.