Send messages using API

Updated at:

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 Phone Number Verification Service (PNVS) 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 can upgrade to an enterprise-verified account or consider SMS Verification Service instead.

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.

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

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 19: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.

    • The review is typically completed within 2 hours. Review hours are 9:00 to 19: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): Simple Message Queue (formerly MNS) 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): Simple Message Queue (formerly MNS) 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.

FAQ