

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 Amazon SNS 发送短信
发送 SMS 消息

本节介绍如何使用 Amazon SNS 发送短信，包括发布到主题、订阅话题的电话号码、设置消息的属性以及直接发布到手机。

## 将短信发布到 Amazon SNS 主题
向主题发布

您可以通过使用多个电话号码订阅 Amazon SNS 主题，一次将一条 SMS 消息发布至这些手机号码。SNS 主题是您可以添加订阅者并随后向所有订阅者发布消息的通信渠道。订阅者会收到发布到该主题的所有消息，直到您取消订阅或订阅者选择不接收来自您的 Amazon 账户的 SMS 消息。

### 使用 Amazon 控制台向主题发送消息


**要创建主题，请执行以下操作**

如果您还没有要发送 SMS 消息的主题，请完成以下步骤。

1. 登录 [Amazon SNS 控制台](https://console.amazonaws.cn/sns/home)。

1. 在控制台菜单中，选择[支持短信收发的区域](https://docs.amazonaws.cn/general/latest/gr/end-user-messaging.html)。

1. 在导航窗格中，选择**主题**。

1. 在 **Topics**（主页）页面上，选择 **Create topic**（创建主题）。

1. 在 **Create topic**（创建主题）页面上的 **Details**（详细信息）下，执行以下操作：

   1. 对于 **Type**（类型），选择 **Standard**（标准）。

   1. 对于 **Name**（名称），输入一个主题名称。

   1. （可选）对于 **Display name**（显示名称），请为您的 SMS 消息输入自定义前缀。在您向主题发送消息时，Amazon SNS 会在显示名称之前加上右尖括号 (>) 和空格。显示名称不区分大小写，Amazon SNS 会将显示名称转换为大写字符。例如，如果主题的显示名称是 `MyTopic`，而消息是 `Hello World!`，则该消息会显示为：

      ```
      MYTOPIC> Hello World!
      ```

1. 选择**创建主题**。主题的名称和 Amazon Resource Name (ARN) 显示在 **Topics**（主题）页面。

**创建 SMS 订阅**

您可以使用订阅通过仅向主题发布一次消息，将 SMS 消息发送给多个收件人。
**注意**  
当您开始使用 Amazon SNS 发送短信时，您的 Amazon 账户处于*短信*沙箱中。SMS 沙盒为您提供了一个安全的环境，让您可以尝试 Amazon SNS 功能，而不会拿您作为 SMS 发件人的声誉冒险。在您的账户位于 SMS 沙盒时，您可以使用 Amazon SNS 的所有功能，但您只能向已验证的目标电话号码发送 SMS 消息。有关更多信息，请参阅 [使用 Amazon SNS 短信沙盒](sns-sms-sandbox.md)。

1. 登录 [Amazon SNS 控制台](https://console.amazonaws.cn/sns/home)。

1. 在导航窗格中，选择**订阅**。

1. 在**订阅**页面上，选择**创建订阅**。

1. 在 **Create subscription**（创建订阅）页面上的 **Details**（详细信息）下，执行以下操作：

   1. 对于 **Topic ARN**（主题 ARN），输入或选择要向其发送 SMS 消息的主题的 Amazon Resource Name (ARN)。

   1. 对于 **Protocol**（协议），选择 **SMS**。

   1. 对于 **Endpoint**（终端节点），输入要订阅主题的电话号码。

1. 选择**创建订阅**。订阅信息显示在 **Subscriptions**（订阅）页面。

   要添加更多电话号码，请重复以下步骤。您还可以添加其他类型的订阅，例如电子邮件。

**发送邮件**

当您向一个主题发布消息时，Amazon SNS 会尝试将该消息传输至订阅该主题的每个电话号码。

1. 在 [Amazon SNS 控制台](https://console.amazonaws.cn/sns/home)中的 **Topics**（主题）页面上，选择要向其发送 SMS 消息的主题的名称。

1. 在主题详细信息页面上，选择**发布消息**。

1. 在 **Publish message to topic**（将消息发布到主题）页面上的 **Message details**（消息详细信息）下，执行以下操作：

   1. 对于 **Subject**（主题），请将该字段留空，除非您的主题包含电子邮件订阅，并且您想要同时发布到电子邮件和 SMS 订阅。Amazon SNS 使用您输入的 **Subject**（主题）作为电子邮件主题行。

   1. （可选）对于 **Time to Live (TTL)**（存活时间 (TTL)），输入 Amazon SNS 向任何移动应用程序终端节点订阅者发送 SMS 消息所需的秒数。

1. 在 **Message body**（消息正文）下，执行以下操作：

   1. 对于 **Message structure**（消息结构），选择 **Identical payload for all delivery protocols**（所有传输协议的负载相同）向订阅了您的主题的所有协议类型发送相同消息。或者，选择 **Custom payload for each delivery protocol**（针对每个传输协议的自定义负载）为不同协议类型的订阅者自定义消息。例如，您可以输入电话号码订阅者的默认消息，以及电子邮件订阅者的自定义消息。

   1. 对于 **Message body to send to the endpoint**（要发送到终端节点的消息正文），输入您的消息或每个传输协议的自定义消息。

      如果您的主题包含显示名称，Amazon SNS 会将其添加到消息，这会增加消息的长度。显示名称的长度是名称的字符数加上两个字符，也就是 Amazon SNS 添加的右尖括号 (>) 和空格。

      有关 SMS 消息大小配额的信息，请参阅 [使用 Amazon SNS 向手机发布短信](#sms_publish-to-phone)。

1. （可选）在**消息属性**中，添加消息元数据，例如时间戳、签名和。 IDs

1. 选择**发布消息**。Amazon SNS 会发送 SMS 消息并显示成功消息。

### 使用向主题发送消息 Amazon SDKs


要使用 S Amazon DK，必须使用您的凭据对其进行配置。有关更多信息，请参阅[和*工具参考指南中的共享配置Amazon SDKs 和*凭据文件](https://docs.amazonaws.cn/sdkref/latest/guide/creds-config-files.html)。

以下代码示例显示了如何：
+ 创建 Amazon SNS 主题。
+ 使用手机号码订阅主题。
+ 向主题发布 SMS 消息，以使所有订阅的电话号码一次接收消息。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。
创建一个主题并返回其 ARN。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.CreateTopicRequest;
import software.amazon.awssdk.services.sns.model.CreateTopicResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class CreateTopic {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicName>

                Where:
                   topicName - The name of the topic to create (for example, mytopic).

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicName = args[0];
        System.out.println("Creating a topic with name: " + topicName);
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String arnVal = createSNSTopic(snsClient, topicName);
        System.out.println("The topic ARN is" + arnVal);
        snsClient.close();
    }

    public static String createSNSTopic(SnsClient snsClient, String topicName) {
        CreateTopicResponse result;
        try {
            CreateTopicRequest request = CreateTopicRequest.builder()
                    .name(topicName)
                    .build();

            result = snsClient.createTopic(request);
            return result.topicArn();

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
为终端节点订阅主题。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.SubscribeRequest;
import software.amazon.awssdk.services.sns.model.SubscribeResponse;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class SubscribeTextSMS {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicArn> <phoneNumber>

                Where:
                   topicArn - The ARN of the topic to subscribe.
                   phoneNumber - A mobile phone number that receives notifications (for example, +1XXX5550100).
                """;

        if (args.length < 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        String phoneNumber = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        subTextSNS(snsClient, topicArn, phoneNumber);
        snsClient.close();
    }

    public static void subTextSNS(SnsClient snsClient, String topicArn, String phoneNumber) {
        try {
            SubscribeRequest request = SubscribeRequest.builder()
                    .protocol("sms")
                    .endpoint(phoneNumber)
                    .returnSubscriptionArn(true)
                    .topicArn(topicArn)
                    .build();

            SubscribeResponse result = snsClient.subscribe(request);
            System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is "
                    + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
设置消息的属性，例如发件人的 ID、最高价格及其类型。消息属性是可选的。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SetSmsAttributesRequest;
import software.amazon.awssdk.services.sns.model.SetSmsAttributesResponse;
import software.amazon.awssdk.services.sns.model.SnsException;
import java.util.HashMap;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class SetSMSAttributes {
    public static void main(String[] args) {
        HashMap<String, String> attributes = new HashMap<>(1);
        attributes.put("DefaultSMSType", "Transactional");
        attributes.put("UsageReportS3Bucket", "janbucket");

        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        setSNSAttributes(snsClient, attributes);
        snsClient.close();
    }

    public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) {
        try {
            SetSmsAttributesRequest request = SetSmsAttributesRequest.builder()
                    .attributes(attributes)
                    .build();

            SetSmsAttributesResponse result = snsClient.setSMSAttributes(request);
            System.out.println("Set default Attributes to " + attributes + ". Status was "
                    + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
向主题发布消息。消息将会发送到每个订阅用户。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class PublishTextSMS {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <message> <phoneNumber>

                Where:
                   message - The message text to send.
                   phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String message = args[0];
        String phoneNumber = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        pubTextSMS(snsClient, message, phoneNumber);
        snsClient.close();
    }

    public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) {
        try {
            PublishRequest request = PublishRequest.builder()
                    .message(message)
                    .phoneNumber(phoneNumber)
                    .build();

            PublishResponse result = snsClient.publish(request);
            System.out
                    .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```

------

## 使用 Amazon SNS 向手机发布短信
发布到移动电话

您可以使用 Amazon SNS 直接向移动电话发送 SMS 消息，而无需订阅 Amazon SNS 主题的电话号码。

**注意**  
如果您想要将一条消息一次发布至多个电话号码，使用电话号码订阅主题会很有用。有关向主题发布 SMS 消息的说明，请参阅 [将短信发布到 Amazon SNS 主题](#sms_publish-to-topic)。

在发送消息时，您可以控制是否对消息进行成本或可靠性传输优化。您还可以指定[发件人 ID 或源号码](channels-sms-originating-identities.md)。如果您使用 Amazon SNS API 或 Amazon SDKs，以编程方式发送消息，则可以为消息传输指定最高价格。

每条 SMS 消息最多能包含 140 字节，字符配额具体取决于编码方案。例如，SMS 消息可以包含：
+ 160 个 GSM 字符
+ 140 个 ASCII 字符
+ 70 个 UCS-2 字符

如果您发布的消息超出大小配额，Amazon SNS 会将其作为多条消息发送，保证每条消息都符合大小配额。消息以整个词为边界，而不会在一个词的中间截断。单个 SMS 发布操作的总大小配额为 1600 字节。

在发送 SMS 消息时，您可以使用 E.164 格式指定电话号码（用于国际电信的标准电话编号结构）。遵循此格式的电话号码最多可包含 15 位数字，并以加号 (\$1) 和国家/地区代码作为前缀。例如，E.164 格式的美国电话号码显示为 \$11 XXX5550100。

### 发送消息（控制台）


1. 登录 [Amazon SNS 控制台](https://console.amazonaws.cn/sns/home)。

1. 在控制台菜单中，选择[支持短信收发的区域](https://docs.amazonaws.cn/general/latest/gr/end-user-messaging.html)。

1. 在导航窗格中，选择**文本消息(SMS)**。

1. 在 **Mobile text messaging (SMS)**（移动文本消息 (SMS)）页面上，选择 **Publish text message**（发布文本消息）。

1. 在 **Publish SMS message**（发布 SMS 消息）页面上，对于 **Message type**（消息类型），选择下列选项之一：
   + **Promotional**（促销）– 不重要的消息，例如营销消息。
   + **Transactional**（事务性）– 为客户事务处理提供支持的重要消息，例如多重身份验证的一次性密码。
**注意**  
此消息级别的设置会覆盖您的账户级别的默认消息类型。您可以从 **Mobile text messaging (SMS)**（移动文本消息 (SMS)）页面的 **Text messaging preferences**（文本消息首选项）部分中设置账户级别的默认消息类型。

   有关促销和事务性消息的定价信息，请参阅[全球 SMS 定价](https://www.amazonaws.cn/sns/sms-pricing/)。

1. 对于 **Destination phone number**（目标电话号码），请输入您想要向其发送消息的电话号码。

1. 对于 **Message**（消息），请输入要发送的消息。

1. （可选）在 **Origination identities**（源身份）下，指定如何向收件人识别自己：
   + 要指定 **Sender ID**（发件人 ID），请键入包含 3-11 个字母数字字符的自定义 ID，其中包括至少一个字母，并且不能包含空格。该发件人 ID 在接收设备上显示为消息发件人。例如，您可以使用自己的企业品牌让消息来源更易于识别。

     对发件人的支持因国家/ and/or 地区 IDs 而异。例如，发送至美国电话号码的消息不显示发件人 ID。有关支持发件人的国家和地区 IDs，请参阅《*Amazon End User Messaging SMS 用户指南》 Amazon End User Messaging SMS*中[支持的 SMS 消息发送的国家和地区](https://docs.amazonaws.cn/sms-voice/latest/userguide/phone-numbers-sms-by-country.html)。

     如果您未指定发件人 ID，以下标识之一将显示为源身份：
     + 在支持长代码的国家/地区，显示长代码。
     + 在仅支持发 IDs 件人的国家/地区，会显示*通知*。

     此消息级别的发件人 ID 会覆盖您在 **Text messaging preferences** 页面中设置的默认发件人 ID。
   + 要指定 **Origination number**（远啊号码），输入一个由 5-14 个数字组成的字符串，以显示为收件人设备上的发件人电话号码。此字符串必须与您在 Amazon Web Services 账户 中为目的地国家/地区配置的起始号码相匹配。起始号码可以是 10DLC 号码、免费电话号码、 person-to-person长码或短码。有关更多信息，请参阅 [Amazon SNS 短信的发起身份](channels-sms-originating-identities.md)。

     如果您未指定源号码，Amazon SNS 会根据您的 Amazon Web Services 账户 配置选择用于 SMS 文本消息的源号码。

1. 如果您要向位于印度的收件人发送 SMS 消息，请展开 **Country-specific attributes**（特定于国家/地区的属性），然后指定以下属性：
   + **Entity ID**（实体 ID）– 向位于印度的收件人发送 SMS 消息的实体 ID 或委托人实体 (PE) ID。此 ID 是印度电信监管局 (TRAI) 提供的 1–50 个字符组成的唯一字符串，用于识别您在 TRAI 中注册的实体。
   + **Template ID**（模板 ID）– 向位于印度的收件人发送 SMS 消息的模板 ID。此 ID 是 TRAI 提供的唯一字符串，该字符串包含 1-50 个字符，用于标识您在 TRAI 中注册的模板。模板 ID 必须与您为邮件指定的发件人 ID 相关联。

   有关向位于印度的收件人发送短信的更多信息，请参阅《Amazon End User Messaging SMS User Guide》**中的 [India sender ID registration process](https://docs.amazonaws.cn/sms-voice/latest/userguide/registrations-sms-senderid-india.html)。

1. 选择**发布消息**。

**提示**  
要从源号码发送 SMS 消息，您还可以在 Amazon SNS 控制台导航面板中选择 **Origination numbers**（源号码）。选择在 **Capabilities**（功能）列中包含 **SMS** 的源号码，然后选择 **Publish text message**（发布文本消息）。

### 发送消息 (Amazon SDKs)


要使用其中一个发送短信 Amazon SDKs，请使用该软件开发工具包中与 Amazon SNS API 中的`Publish`请求相对应的 API 操作。通过此请求，您可以直接向电话号码发送 SMS 消息。您也可使用 `MessageAttributes` 参数设置以下属性名称的值：

**`AWS.SNS.SMS.SenderID`**  
包含 3-11 个字母数字字符或连字符 (-) 的自定义 ID，其中包含至少一个字母，并且不能包含空格。该发件人 ID 在接收设备上显示为消息发件人。例如，您可以使用自己的企业品牌让消息来源更易于识别。  
对发件人的支持因国家或地区 IDs 而异。例如，发送至美国电话号码的消息不显示发件人 ID。有关支持发件人的国家或地区的列表 IDs，请参阅《*Amazon End User Messaging SMS 用户指南》 Amazon End User Messaging SMS*中[支持使用发送短信的国家和地区](https://docs.amazonaws.cn/sms-voice/latest/userguide/phone-numbers-sms-by-country.html)。  
如果您未指定发件人 ID，则在支持的国家或地区中[长代码](https://docs.amazonaws.cn/sms-voice/latest/userguide/phone-numbers-request-long-code.html)会显示为发件人 ID。对于要求使用按字母顺序排列发件人 ID 的国家和地区，*NOTICE* 显示为发件人 ID。  
此消息级别的属性会覆盖您可以通过 `SetSMSAttributes` 请求设置的账户级别属性 `DefaultSenderID`。

**`AWS.MM.SMS.OriginationNumber`**  
一个由 5—14 个数字组成的自定义字符串，其中可以包括一个可选的前导加号 (`+`)。此数字字串在接收设备上显示为发件人的电话号码。该字符串必须与您的 Amazon 账户中为目的地国家/地区配置的发件人号码相匹配。发起号码可以是 10DLC 号码、免费电话号码、 person-to-person (P2P) 长码或短码。有关更多信息，请参阅《Amazon End User Messaging SMS User Guide》中的** [Phone numbers](https://docs.amazonaws.cn/sms-voice/latest/userguide/phone-numbers.html)。  
如果您未指定发货号，Amazon SNS 会根据 Amazon 您的账户配置选择发货号。

**`AWS.SNS.SMS.MaxPrice`**  
您愿意用于发送 SMS 消息的最高价格（以美元为单位）。如果 Amazon SNS 确定发送消息会产生超出您最高价格的成本，则它不会发送消息。  
如果您的 month-to-date短信费用已超过为该属性设置的配额，则此`MonthlySpendLimit`属性无效。您可以使用 `SetSMSAttributes` 请求设置 `MonthlySpendLimit` 属性。  
如果您发送消息至 Amazon SNS 主题，则该最高价格适用于传输给订阅该主题的每个电话号码的每条消息。

**`AWS.SNS.SMS.SMSType`**  
要发送的消息类型：  
+ **`Promotional`**（默认）– 不重要的消息，例如营销消息。
+ **`Transactional`** – 为客户事务处理提供支持的重要消息，例如多重身份验证的一次性密码。
此消息级别的属性会覆盖您可以通过 `SetSMSAttributes` 请求设置的账户级别属性 `DefaultSMSType`。

**`AWS.MM.SMS.EntityId`**  
只有向位于印度的收件人发送 SMS 消息时，才需要此属性。  
这是您用于向位于印度的收件人发送 SMS 消息的实体 ID 或委托人实体 (PE) ID。此 ID 是印度电信监管局 (TRAI) 提供的 1–50 个字符组成的唯一字符串，用于识别您在 TRAI 中注册的实体。

**`AWS.MM.SMS.TemplateId`**  
只有向位于印度的收件人发送 SMS 消息时，才需要此属性。  
这是您向位于印度的收件人发送 SMS 消息的模板。此 ID 是 TRAI 提供的唯一字符串，该字符串包含 1-50 个字符，用于标识您在 TRAI 中注册的模板。模板 ID 必须与您为邮件指定的发件人 ID 相关联。

#### 发送消息


以下代码示例演示了如何使用 Amazon SNS 发布 SMS 消息。

------
#### [ .NET ]

**适用于 .NET 的 Amazon SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)中查找完整示例，了解如何进行设置和运行。

```
namespace SNSMessageExample
{
    using System;
    using System.Threading.Tasks;
    using Amazon;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    public class SNSMessage
    {
        private AmazonSimpleNotificationServiceClient snsClient;

        /// <summary>
        /// Initializes a new instance of the <see cref="SNSMessage"/> class.
        /// Constructs a new SNSMessage object initializing the Amazon Simple
        /// Notification Service (Amazon SNS) client using the supplied
        /// Region endpoint.
        /// </summary>
        /// <param name="regionEndpoint">The Amazon Region endpoint to use in
        /// sending test messages with this object.</param>
        public SNSMessage(RegionEndpoint regionEndpoint)
        {
            snsClient = new AmazonSimpleNotificationServiceClient(regionEndpoint);
        }

        /// <summary>
        /// Sends the SMS message passed in the text parameter to the phone number
        /// in phoneNum.
        /// </summary>
        /// <param name="phoneNum">The ten-digit phone number to which the text
        /// message will be sent.</param>
        /// <param name="text">The text of the message to send.</param>
        /// <returns>Async task.</returns>
        public async Task SendTextMessageAsync(string phoneNum, string text)
        {
            if (string.IsNullOrEmpty(phoneNum) || string.IsNullOrEmpty(text))
            {
                return;
            }

            // Now actually send the message.
            var request = new PublishRequest
            {
                Message = text,
                PhoneNumber = phoneNum,
            };

            try
            {
                var response = await snsClient.PublishAsync(request);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error sending message: {ex}");
            }
        }
    }
}
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [Publish](https://docs.amazonaws.cn/goto/DotNetSDKV3/sns-2010-03-31/Publish)。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
/**
 * Publish SMS: use Amazon Simple Notification Service (Amazon SNS) to send an SMS text message to a phone number.
 * Note: This requires additional AWS configuration prior to running example. 
 * 
 *  NOTE: When you start using Amazon SNS to send SMS messages, your AWS account is in the SMS sandbox and you can only
 *  use verified destination phone numbers. See https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html.
 *  NOTE: If destination is in the US, you also have an additional restriction that you have use a dedicated
 *  origination ID (phone number). You can request an origination number using Amazon Pinpoint for a fee.
 *  See https://aws.amazon.com/blogs/compute/provisioning-and-using-10dlc-origination-numbers-with-amazon-sns/ 
 *  for more information. 
 * 
 *  <phone_number_value> input parameter uses E.164 format. 
 *  For example, in United States, this input value should be of the form: +12223334444
 */

//! Send an SMS text message to a phone number.
/*!
  \param message: The message to publish.
  \param phoneNumber: The phone number of the recipient in E.164 format.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::publishSms(const Aws::String &message,
                             const Aws::String &phoneNumber,
                             const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::PublishRequest request;
    request.SetMessage(message);
    request.SetPhoneNumber(phoneNumber);

    const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request);

    if (outcome.IsSuccess()) {
        std::cout << "Message published successfully with message id, '"
                  << outcome.GetResult().GetMessageId() << "'."
                  << std::endl;
    }
    else {
        std::cerr << "Error while publishing message "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  有关 API 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [Publish](https://docs.amazonaws.cn/goto/SdkForCpp/sns-2010-03-31/Publish)。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class PublishTextSMS {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <message> <phoneNumber>

                Where:
                   message - The message text to send.
                   phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String message = args[0];
        String phoneNumber = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        pubTextSMS(snsClient, message, phoneNumber);
        snsClient.close();
    }

    public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) {
        try {
            PublishRequest request = PublishRequest.builder()
                    .message(message)
                    .phoneNumber(phoneNumber)
                    .build();

            PublishResponse result = snsClient.publish(request);
            System.out
                    .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [Publish](https://docs.amazonaws.cn/goto/SdkForJavaV2/sns-2010-03-31/Publish)。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun pubTextSMS(
    messageVal: String?,
    phoneNumberVal: String?,
) {
    val request =
        PublishRequest {
            message = messageVal
            phoneNumber = phoneNumberVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.publish(request)
        println("${result.messageId} message sent.")
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Kotlin API Reference》**中的 [Publish](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Sends a text message (SMS message) directly to a phone number using Amazon SNS.
 *
 * This code expects that you have AWS credentials set up per:
 * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
 */

$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$message = 'This message is sent from a Amazon SNS code sample.';
$phone = '+1XXX5550100';

try {
    $result = $SnSclient->publish([
        'Message' => $message,
        'PhoneNumber' => $phone,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  有关更多信息，请参阅《适用于 PHP 的 Amazon SDK 开发人员指南》[https://docs.amazonaws.cn/sdk-for-php/v3/developer-guide/sns-examples-sending-sms.html#publish-to-a-text-message-sms-message](https://docs.amazonaws.cn/sdk-for-php/v3/developer-guide/sns-examples-sending-sms.html#publish-to-a-text-message-sms-message)。
+  有关 API 详细信息，请参阅 *适用于 PHP 的 Amazon SDK API 参考*中的 [Publish](https://docs.amazonaws.cn/goto/SdkForPHPV3/sns-2010-03-31/Publish)。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
class SnsWrapper:
    """Encapsulates Amazon SNS topic and subscription functions."""

    def __init__(self, sns_resource):
        """
        :param sns_resource: A Boto3 Amazon SNS resource.
        """
        self.sns_resource = sns_resource


    def publish_text_message(self, phone_number, message):
        """
        Publishes a text message directly to a phone number without need for a
        subscription.

        :param phone_number: The phone number that receives the message. This must be
                             in E.164 format. For example, a United States phone
                             number might be +12065550101.
        :param message: The message to send.
        :return: The ID of the message.
        """
        try:
            response = self.sns_resource.meta.client.publish(
                PhoneNumber=phone_number, Message=message
            )
            message_id = response["MessageId"]
            logger.info("Published message to %s.", phone_number)
        except ClientError:
            logger.exception("Couldn't publish message to %s.", phone_number)
            raise
        else:
            return message_id
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [Publish](https://docs.amazonaws.cn/goto/boto3/sns-2010-03-31/Publish)。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    " iv_phone_number = '+12065550101' - Phone number in E.164 format
    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_phonenumber = iv_phone_number
          iv_message = iv_message ).
        MESSAGE 'Message published to phone number.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Phone number does not exist.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 详细信息，请参阅《Amazon SDK for SAP ABAP API 参考》**中的 [Publish](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

------