Send SMS messages using an API

更新时间:
复制 MD 格式

Short Message Service provides APIs for sending messages, querying sending statuses, and more. You can call these APIs to apply for signatures and templates, and then send SMS messages to your target users.

Choose a method to call the Short Message Service API based on your business requirements and technical expertise:

  • OpenAPI Explorer

    This method is recommended for developers who prefer an interactive UI or are new to Alibaba Cloud. You can use OpenAPI Explorer to debug APIs and generate SDK request examples.

  • Short Message Service SDK

    SDKs are available for multiple programming languages, including Java, Go, C#, PHP, Node.js/TypeScript, and Python. Using an SDK to integrate Short Message Service improves your development efficiency.

    If you are new to Short Message Service or have limited programming experience, we recommend using an SDK. The SDKs handle underlying logic such as signature authentication, timeouts, and automatic retries. This lets you focus on business parameters like phone numbers, signatures, and templates, simplifying integration and removing the need to understand complex signing algorithms or request formats.

  • Build your own API wrapper (not recommended)

    Alibaba Cloud SDKs handle the underlying logic for signing, timeouts, and retries. We recommend that you use an SDK to reduce development costs. Building your own API wrapper requires handling low-level details, including the signing algorithm, timeout management, retries, and request formatting. This requires significant development effort, especially for beginners. If you have specific customization needs and are familiar with the signing mechanism, see SendSms and signature sample code.

This topic shows you how to use an SDK to interact with Short Message Service. You can first use the OpenAPI Explorer to explore and test the Short Message Service API, and then follow this guide to start integrating the API. The overall process is as follows:

image

Before you begin

Item

Description

Related documents

Account registration

Real-name verification

Due to real-name verification requirements for SMS signatures, you must provide enterprise qualification information to use Short Message Service.

  • Individual verification: Indicates the account holder is an individual. Short Message Service does not support signature real-name filing for individual qualifications. We recommend that you use the SMS Authentication product, which allows you to apply for signatures and templates without providing qualifications. If you have an enterprise qualification, you can upgrade your Alibaba Cloud account to an enterprise-verified account or add a third-party enterprise qualification.

  • Enterprise verification: Indicates the account holder is an enterprise or government entity. You must provide self-use or third-party enterprise qualifications to use Short Message Service.

Important

Under current real-name verification requirements for SMS signatures, an individual account's self-use qualification cannot pass signature real-name filing. Individual users must use the SMS Authentication product or upgrade to an enterprise-verified account.

Usage notes

Service activation

Log on to the Short Message Service console to enable the service.

User permissions

Note

An Alibaba Cloud account has root-level permissions, so we recommend using a RAM user for API calls and daily operations.

Go to the RAM console and click a RAM user's name to view their permissions. Ensure that the RAM user that you use to make API calls has the required permissions for Short Message Service:

  • AliyunDysmsFullAccess: The permission to manage Short Message Service.

Create a RAM user

Manage RAM user permissions

Customize authorization information

AccessKey ID

You can log on to the RAM console and click a RAM user's name to view the AccessKey ID.

Create an AccessKey pair

AccessKey Secret

The AccessKey Secret cannot be viewed again after it is created. If you do not have a local backup, we recommend that you create a new AccessKey pair.

Configure alerts

To ensure business stability and fund security, we recommend that you log on to the console, navigate to the General Settings > Domestic Message Settings page, set up a contact, and then enable and configure Verification code anti-fraud monitoring, Sending volume alert, Resource plan balance alert, and Sending frequency alert. When an alert is triggered, the platform notifies the specified contact, allowing for immediate action.

Note

We recommend that you read Anti-fraud for verification codes to learn more about how to prevent verification code abuse.

Sending volume alerts

Resource plan balance alerts

Sending frequency alerts

Set up your environment

This topic uses Java as an example. For more information about other programming languages and their SDK installation methods, see Installation and usage.

  1. Check your Java environment: You must use Java 8 or later. For information about how to set up a Java environment, see Set up a Java development environment on Windows.

  2. Install the SDK: Add a Maven dependency to install the Short Message Service SDK.

    Recommended SDK version: Use the V2.0 SDK with artifact ID dysmsapi20170525. JDK 1.8 and later are supported. The V1.0 SDK (alibabacloud-dysmsapi20170525) is still functional but is no longer recommended.

    Open the pom.xml file in your Maven project, add the following dependency within the <dependencies> tag, and replace the-latest-version with the latest version number. After you save the file, reload your Maven dependencies.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>dysmsapi20170525</artifactId>
      <!-- Replace 'the-latest-version' with the latest version number: https://mvnrepository.com/artifact/com.aliyun/dysmsapi20170525 -->
      <version>the-latest-version</version>
    </dependency>

    If Maven is not available in your environment, manually download all required JAR files and add them to your project classpath.

    PHP projects: If you encounter a missing dependency error during SDK installation, run the following command to install the required package:

    composer require alibabacloud/tea-utils

    Legacy environments: The official SDK does not support environments such as VB6.0. We recommend upgrading your development environment. Alternatively, use the Alibaba Cloud CLI or AI-generated self-signed code as a workaround.

  3. Configure environment variables: To avoid security risks from hardcoding your AccessKey in your code, we recommend that you store the AccessKey in an environment variable and read it at runtime. After configuration, restart or refresh your build and runtime environment, including your IDE, command-line interface, and other desktop applications and background services, to ensure the latest system environment variables are loaded.

  4. Configure a proxy (optional): If you need to use a proxy server, configure it in the SDK. For more information, see Proxy configuration.

API basics

The following table describes the basic API information for Short Message Service.

API version

2017-05-25

API style

RPC

Service endpoint

(endpoint)

Use dysmsapi.aliyuncs.com.

Use port 80 for HTTP calls and port 443 for HTTPS calls.

Before you call an API, we recommend that you read the parameter specifications and usage instructions. Online debugging | API documentation

Note the following when configuring your endpoint:

  • Domain name, not IP address — The IP addresses behind dysmsapi.aliyuncs.com are dynamic and change without notice. Configure your firewall or security group rules to allow traffic by domain name, not by specific IP address. If your environment only supports IP whitelisting, you must resolve the domain yourself and update the allowlist regularly.

  • Public internet access only — No IP whitelisting is required on the Alibaba Cloud side. As long as your server has public internet access, it can call the API.

  • No path-based routing — Do not append the action name to the endpoint URL (for example, do not call dysmsapi.aliyuncs.com/SendSms). The endpoint is a fixed domain; the API action is specified in the request parameters.

  • Browser access not supported — This API uses RPC-style calling conventions and cannot be called directly from a browser.

  • RegionId parameter — When sending domestic SMS messages (mainland China), the RegionId parameter (for example, cn-hangzhou) does not affect message delivery. You can use any valid region ID.

  • Supported protocols — Only RESTful/OpenAPI is supported. SOAP and WSDL protocols are not supported.

API call flow

image
  1. Apply for an SMS qualification: Call the SubmitSmsQualification API. The qualification information must comply with the qualification material specifications. You can apply for an SMS signature only after your qualification is approved.

    • Due to real-name filing requirements for SMS signatures, the volume of qualification review tickets has increased, which may extend the review time. The review is typically completed within 2 business days.

    • To check the review status using the API, first call the QuerySmsQualificationRecord API to list qualifications. Then, use the WorkOrderId output parameter to call the QuerySingleSmsQualification API and query the status of a specific qualification.

  2. Apply for an SMS signature: Call the CreateSmsSign API. The signature information must comply with the SMS signature specifications. You can apply for a template only after the signature is approved.

    Note

    When you call the CreateSmsSign operation, the QualificationId parameter is required. Make sure that you have completed the qualification review and obtained the qualification ID before you call the operation.

    • If you apply for a signature for third-party use, you must upload a letter of authorization. Before you apply for an SMS signature, we recommend that you follow the letter of authorization specifications and call the CreateSmsAuthorizationLetter API to create a letter of authorization.

    • The review is typically completed within 2 hours. Review hours are 9:00 to 21:00, Monday to Sunday. The process may be delayed during public holidays.

    • You can check the review status by using an API or a receipt:

      API

      Call the GetSmsSign API to query the signature status, or call the QuerySmsSignList API to query the signature list. Check the status based on the AuditStatus output parameter.

      Receipt

      To use receipts, you must configure and integrate them. For more information, see Configure receipts. Only HTTP batch push mode is supported.

      SignSmsReport (signature review status)

    • Signature real-name filing: New signatures are automatically submitted for filing after approval. For existing signatures, go to the Signature Management page to verify their status and manually submit them for filing. Carriers block messages sent with unfiled signatures. For more information, see Instructions.

      Important

      Before registration is complete, messages may fail to send. The following error code may be returned:

      • PORT_NOT_REGISTERED: The port number being used has not completed the enterprise identity verification process.

      • Carrier registration typically takes 7 to 10 business days but can take longer, as carriers do not provide a guaranteed timeframe. Apply for qualifications and signatures in advance and reserve time for testing before going live.

      If filing fails, follow the instructions in the filing result details in the console. For more information, see Signature real-name filing.

  3. Apply for an SMS template: Call the CreateSmsTemplate API. The template content must comply with the SMS template specifications. You can send SMS messages only after the template is approved.

    Note

    When you call the CreateSmsTemplate interface, the RelatedSignName parameter is required. Make sure that you have an approved signature and specify its name for this parameter.

    • The signature that you associate when you apply for a template is for review purposes only and is independent of the signature that you use to send messages.

    • Templates for domestic SMS messages and international or Hong Kong/Macao/Taiwan SMS messages are not interchangeable.

    • The review is typically completed within 2 hours. Review hours are 9:00 to 21:00, Monday to Sunday. The process may be delayed during public holidays.

    • You can check the review status by using an API or a receipt:

      API

      Call the GetSmsTemplate API to query the template status, or call the QuerySmsTemplateList API to query the template list. Check the status based on the AuditStatus output parameter.

      Receipt

      To use receipts, you must configure and integrate them. For more information, see Configure receipts. Only HTTP batch push mode is supported.

      TemplateSmsReport (template review status)

  4. Send SMS messages: Call the SendSms API, or call the SendBatchSms API to send messages in batches.

    • We recommend that you wait until the signature filing status changes to "Filed and Pending Verification" before you send messages in bulk. You can use phone numbers from the three major carriers and send messages in small, frequent batches to send verification codes or notification messages for testing. During the system's detection period, we suggest conducting thorough tests. If the test messages have a satisfactory success rate, the filing status changes to "Filing Successful". If the filing status is not "Filing Successful", follow the instructions in the filing verification section.

    • Ensure that your account has a sufficient balance before sending SMS messages. For more information, see Billing overview.

  5. View SMS sending details: You can use APIs or receipts to view SMS sending details.

    API

    Call the QuerySendDetails API to query the status of sent SMS messages.

    Receipt

    To use receipts, you must configure and integrate them. For more information, see Configure receipts. The following two modes are supported:

    SmsReport (status report reception): Lightweight Message Queue Consumer Mode | HTTP Batch Push Mode

  6. Receive inbound messages: An inbound message is a reply from a user to an SMS message you have sent. To receive inbound messages, you must configure receipts.

    Receipt

    To use receipts, you must configure and integrate them. For more information, see Configure receipts. The following two modes are supported:

    SmsUp (inbound message reception): Lightweight Message Queue Consumer Mode | HTTP Batch Push Mode

For more API information, see API overview.

Code example

The following code provides an example of how to send an SMS message using the SDK (calling the SendSms API). Replace the placeholder parameter values as described in the code comments.

package com.aliyun.sample;

import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
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 environment variables are set in your runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Configure the AccessKey Secret. Make sure the environment variables are set in your runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
                // The System.getenv() method returns system environment variables. After you set environment variables, enter the variable names here. Do not hard-code your AccessKey values.
        
        // Configure the endpoint.
        config.endpoint = "dysmsapi.aliyuncs.com";

        return new Client(config);
    }

    public static void main(String[] args) throws Exception {
        // Initialize the request client.
        Client client = Sample.createClient();

        // Create a request object. Specify the parameter values.
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers("1390000****")
                .setSignName("Alibaba Cloud")
                .setTemplateCode("SMS_15305****")
                .setTemplateParam("{\"name\":\"John Doe\",\"number\":\"1390000****\"}");

        // Obtain the response object.
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

        // The response includes the body and headers from the server.
        System.out.println(toJSONString(sendSmsResponse));
    }
}

Go to the OpenAPI Explorer to view complete SDK request examples in different languages. To build your own API requests, refer to SendSms and signature sample code.

SDK integration best practices

Follow these recommendations when integrating the SDK in a production environment:

  • Reuse the Client instance — Do not create a new Client instance on every API call. Initialize the client once and reuse it as a singleton throughout your application's lifecycle. Creating a new client per request causes unnecessary connection overhead.

  • Configure timeouts — Set both connectTimeout and readTimeout to at least 1,000 milliseconds (1 second). Without timeout limits, a blocked synchronous call can stall threads indefinitely.

  • Async calling notes:

    • Python SDK: If you call the SDK from a non-main thread, use the async method variant to avoid blocking the thread.

    • Java SDK: When using async calls, do not manage the Client instance with try-with-resources. The client must remain open until the async future completes. Closing it before the future finishes will cause the call to fail.

  • Serialization compatibility — The Druid JSONUtils library does not support SDK response objects. Use getBody() to extract the raw response string, or use FastJSON or Jackson to serialize the response.

  • Environment variable reload — After setting ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET as environment variables, restart your IDE, command-line session, and all related processes before the new values take effect.

FAQ

Q: Why does my message still show the old signature after I updated my SMS signature?

The signature used when sending a message is determined solely by the SignName parameter in the SendSms API request. It is not affected by which signature is associated with a template in the console. After you replace your signature, you must update the SignName value in your business code.

Note

Note the following:

  • The new signature must have passed review and completed real-name filing before it can be used.

  • Initial message success rates may fluctuate during the new signature's carrier detection period. This is expected behavior.

Q: Where can I obtain my AccessKey, signature name, and template CODE?

Parameter

Where to get it

Notes

AccessKey ID / AccessKey Secret

Create an AccessKey pair in the RAM console.

The AccessKey Secret is shown only once at creation time. If you lose it, create a new pair. One AccessKey pair is shared across all templates and signatures — no need to create separate credentials per template. The key is active immediately with no review required.

Signature name

Go to Signature Management in the Short Message Service console.

Use only signatures with "Approved" status. The value you pass in SignName must match the console entry exactly, including any brackets in the name.

Template CODE

Go to Template Management in the Short Message Service console.

Template CODEs start with SMS_.

Third-party platform APPkey

When configuring third-party platforms, the field labeled "APPkey" typically corresponds to your AccessKey ID.

Q: Can the SMS API be called directly from frontend JavaScript, or used with third-party platforms?

Frontend JavaScript: Pure frontend JavaScript cannot call the Short Message Service API directly. No JavaScript browser SDK is provided. All API calls must go through a backend service to avoid exposing your AccessKey credentials.

Third-party platform integration: When integrating with platforms such as TikTok, Lark, or Sangfor AC, use the standard API parameters:

  • Endpoint: dysmsapi.aliyuncs.com

  • AccessKey ID and AccessKey Secret

  • Signature name and template CODE

No special interface is required. The standard Alibaba Cloud SMS API applies.

Custom development: Alibaba Cloud does not provide custom development services. Your own technical team must implement the business logic that triggers SMS sending.

Q: Can domestic SMS and international/Hong Kong/Macao/Taiwan SMS use the same API?

No. The two services use separate APIs:

SMS type

API version

API operation

Domestic SMS (mainland China)

2017-05-25

SendSms

International / Hong Kong / Macao / Taiwan SMS

2018-05-25

SendMessageToGlobe

The two APIs have different signatures, templates, and compliance requirements and cannot be used interchangeably. Using the wrong API returns errors such as SMS_CONTENT_CODE_ILLEGAL or Specified parameter Region is not valid.

Your AccessKey pair works for both services — no need to create separate credentials for international SMS.

Q: How do I troubleshoot "template not found" or "invalid signature" errors?

Work through the following checklist:

  1. Account ownership: Confirm that the AccessKey you are using belongs to the same Alibaba Cloud account that owns the signature and template.

  2. Approval status: Confirm that both the template and signature have "Approved" status in the console.

  3. Exact match: Verify that the TemplateCode value (starting with SMS_) and SignName value in your request exactly match what is shown in the console. Remove any leading or trailing spaces.

  4. Correct API version: Confirm that you are not using the international SMS API (2018-05-25 / SendMessageToGlobe) to send domestic messages, or vice versa.

  5. Real-name filing: If you receive an "invalid signature" error, check whether the signature has completed real-name filing in the console. Carriers block messages sent with unfiled signatures.

Video tutorial

The video tutorial is in Chinese only.