

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Amazon SNS 傳送簡訊
<a name="sms_sending-overview"></a>

本節說明如何使用 Amazon SNS 傳送簡訊，包括發佈至主題、訂閱主題的電話號碼、設定訊息屬性，以及直接發佈至行動電話。

## 將 SMS 訊息發佈至 Amazon SNS 主題
<a name="sms_publish-to-topic"></a>

您可以透過訂閱電話號碼到 Amazon SNS 主題，一次發佈單一簡訊至多組電話號碼。SNS 主題是您可以新增訂閱者然後發佈訊息至所有那些訂閱者的通訊通道。訂閱者會收到發佈至主題的所有訊息，直到您取消訂閱，或訂閱者選擇不接收來自您 AWS 帳戶的簡訊為止。

### 使用 AWS 主控台傳送訊息至主題
<a name="sms_publish-to-topic_console"></a>

**若要建立主題**

如果您尚未擁有想要傳送簡訊的主題，請完成下列步驟。

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 在主控台功能表中，選擇[支援簡訊的區域](https://docs.aws.amazon.com/general/latest/gr/end-user-messaging.html)。

1. 在導覽窗格中，選擇 **Topics** (主題)。

1. 在 **Topics** (主題) 頁面上，選擇 **Create topic** (建立主題)。

1. 在 **Create topic** (建立主題) 頁面上，於 **Details** (詳細資料) 下方，執行下列動作：

   1. 針對 **Type** (類型)，選擇 **Standard** (標準)。

   1. 針對 **Name** (名稱)，輸入主題名稱。

   1. (選用) 對於 **Display name** (顯示名稱)，輸入簡訊的自訂字首。傳送訊息至主題時，Amazon SNS 會將顯示名稱置於前面，後面加上右尖括號 (>) 和空格。顯示名稱不區分大小寫，Amazon SNS 會將顯示名稱轉換為大寫字元。例如，如果主題的顯示名稱為 `MyTopic`，而訊息為 `Hello World!`，則訊息將顯示為：

      ```
      MYTOPIC> Hello World!
      ```

1. 請選擇**建立主題**。主題的名稱和 Amazon 資源名稱 (ARN) 會顯示在**主題**頁面上。

**建立簡訊訂閱**

訂閱可讓您只要發佈一次訊息到主題，就能傳送簡訊至多位收件人。
**注意**  
當您開始使用 Amazon SNS 傳送簡訊時， AWS 您的帳戶位於*簡訊沙盒*中。簡訊沙盒為您提供了一個安全的環境，讓您嘗試 Amazon SNS 功能，而不會危及您作為簡訊寄件者的聲譽。當您的帳戶位在簡訊沙盒中時，您可以使用 Amazon SNS 的所有功能，但您只能傳送簡訊給已驗證的目的地電話號碼。如需詳細資訊，請參閱[使用 Amazon SNS SMS 沙盒](sns-sms-sandbox.md)。

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 在導覽窗格中，選擇**訂閱**。

1. 在 **Subscriptions** (訂閱) 頁面，選擇 **Create subscription (建立訂閱)**。

1. 在 **Create subscription** (建立訂閱) 頁面上，於 **Details** (詳細資訊) 區段中，執行以下作業：

   1. 適用於 **ARN 主題**中，輸入或選擇您要傳送簡訊之主題的 Amazon 資源名稱 (ARN)。

   1. 針對 **Protocol** (通訊協定)，選擇 **SMS**。

   1. 針對 **Endpoint** (端點)，輸入您要訂閱主題的電話號碼。

1. 選擇**建立訂閱**。訂閱資訊會顯示於 **Subscriptions** (訂閱) 頁面上。

   若要新增更多電話號碼，請重複這些步驟。您也可以新增其他類型的訂閱，例如電子郵件。

**傳送訊息**

當您發佈訊息至主題時，Amazon SNS 會嘗試傳遞該訊息到每個已訂閱主題的電話號碼。

1. 在 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)中，在**主題**頁面上，選擇您要傳送簡訊的主題名稱。

1. 在主題詳細資訊頁面上，選擇 **Publish message** (發佈訊息)。

1. 在 **Publish message to topic** (發佈訊息至主題) 頁面上，**Message details** (訊息詳細資訊) 下方，執行下列步驟：

   1. 將 **Subject** (主旨) 欄位留白，除非您的主題包含電子郵件訂閱而您想要發佈至電子郵件和簡訊訂閱二者。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 所新增的右尖括號 (>) 和空格兩個字元。

      如需有關簡訊大小配額的詳細資訊，請參閱 [使用 Amazon SNS 將簡訊發佈到行動電話](#sms_publish-to-phone)。

1. (選擇性) 對於 **Message attributes** (訊息屬性)，新增郵件中繼資料，例如時間戳記、簽名和 ID。

1. 選擇 **Publish message** (發佈訊息)。Amazon SNS 傳送簡訊並顯示成功訊息。

### 使用 AWS SDKs 傳送訊息至主題
<a name="sms_publish-to-topic_sdk"></a>

若要使用 AWS SDK，您必須使用登入資料進行設定。如需詳細資訊，請參閱 *AWS 開發套件和工具參考指南*中的[共享的配置和認證文件](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)。

以下代碼範例顯示做法：
+ 建立 Amazon SNS 主題。
+ 使用手機號碼訂閱主題。
+ 將簡訊發布至主題，讓所有訂閱的電話號碼一次接收訊息。

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

**SDK for Java 2.x**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](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 將簡訊發佈到行動電話
<a name="sms_publish-to-phone"></a>

您可以使用 Amazon SNS 直接將簡訊傳送到行動電話，而無需訂閱 Amazon SNS 主題的電話號碼。

**注意**  
如果您想要一次將一個訊息傳送至多個電話號碼，訂閱電話號碼到主題仍然相當實用。如需將簡訊發布至主題的指示，請參閱 [將 SMS 訊息發佈至 Amazon SNS 主題](#sms_publish-to-topic)。

傳送訊息時，您可以控制是否針對成本或可靠傳遞將訊息最佳化。您也可以指定[寄件者 ID 或來源編號](channels-sms-originating-identities.md)。如果您使用 Amazon SNS API 或 AWS SDKs 以程式設計方式傳送訊息，您可以指定訊息傳遞的最高價格。

每則簡訊最多可包含 140 個位元組，而字元配額則依編碼機制而定。例如，簡訊可包含：
+ 160 個 GSM 字元
+ 140 個 ASCII 字元
+ 70 個 UCS-2 字元

如果您發布超過大小配額的簡訊，Amazon SNS 會將其分割為多個訊息傳送，每一個均在大小配額以內。訊息不會在字詞中間切割，而是在整個字詞的邊界切割。單一簡訊發布動作的總計大小配額是 1,600 位元組。

傳送簡訊時，您可以使用 E.164 格式指定電話號碼，這是用於國際電信的標準電話號碼結構。遵循此格式的電話號碼最多可以有 15 位數，前面加上加號 (\$1) 字元和國碼。例如，E.164 格式的美國電話號碼顯示為 \$11XXX5550100。

### 傳送訊息 (主控台)
<a name="sms_publish_console"></a>

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 在主控台功能表中，選擇[支援簡訊的區域](https://docs.aws.amazon.com/general/latest/gr/end-user-messaging.html)。

1. 在導覽窗格中，選擇 **Text messaging (SMS)** (簡訊 (SMS))。

1. 在**Mobile text messaging (SMS)** (行動裝置簡訊 (SMS))頁面中，選擇 **Publish text message** (發布簡訊)。

1. 在 **Publish SMS message** (發布簡訊) 頁面上的 **Message type** (訊息類型) 下，選擇下列其中一個項目：
   + **Promotional** (促銷) - 非重要訊息，例如行銷訊息。
   + **交易** - 支援客戶交易的重要訊息，例如多重要素驗證用的一次性密碼。
**注意**  
此訊息層級設定會覆寫您的帳戶層級預設訊息類型。您可以在 **Mobile text messaging (SMS)** (行動裝置簡訊 (SMS)) 頁面上的 **Text messaging preferences** (文字簡訊偏好設定) 區段設定帳戶層級的預設郵件類型。

   如需有關宣傳和交易訊息的定價資訊，請參閱 [Worldwide SMS Pricing](https://aws.amazon.com/sns/sms-pricing/) (全球簡訊定價)。

1. 對於 **Destination phone number** (目的地電話號碼)，請輸入您要傳送訊息的電話號碼。

1. 對於 **Message** (訊息)，請輸入要傳送的訊息。

1. (選擇性) 在 **Origination identities** (來源身分) 下，指定如何向收件者識別您的身分：
   + (選用) 若要指定 **Sender ID** (寄件者 ID)，請輸入包含 3-11 個英數字元 (至少包括一個字母且無空格) 的自訂 ID。寄件者 ID 會在接收的裝置上顯示為訊息寄件者。例如，您可以使用您的商業品牌使訊息來源更容易辨識。

     支援依國家和/或區域而異的寄件者 ID。例如，傳送到美國電話號碼的訊息不會顯示寄件者 ID。如需支援寄件者 IDs的國家/地區和區域，請參閱*AWS End User Messaging SMS 《 使用者指南*》中的[使用 傳送簡訊的支援國家/地區和區域 AWS End User Messaging SMS](https://docs.aws.amazon.com/sms-voice/latest/userguide/phone-numbers-sms-by-country.html)。

     如果您未指定寄件者 ID，下列其中一個項目會顯示為來源身分：
     + 在支援長碼的國家/地區，會顯示長碼。
     + 在僅支援寄件者 ID 的國家/地區，會顯示 *NOTICE*。

     此訊息級寄件者 ID 會覆寫您在 **Text messaging preferences** (簡訊偏好設定) 頁面設定的預設寄件者 ID。
   + 若要指定**來源號碼**，輸入 5-14 個號碼的字串，以在接收者裝置上顯示為寄件者的電話號碼。此字串必須符合在目的地國家 AWS 帳戶 /地區 中設定的起始號碼。來源號碼可以是 10DLC 號碼、免付費號碼、人對人長碼或短碼。如需詳細資訊，請參閱[Amazon SNS SMS 訊息的來源身分](channels-sms-originating-identities.md)。

     如果您沒有指定來源號碼，Amazon SNS 會根據您的 AWS 帳戶 組態選擇。

1. 如果您要傳送簡訊給印度收件人，請展開 **Country-specific attributes** (特定國家屬性)，並指定下列屬性：
   + **實體 ID** - 傳送簡訊給印度收件人的實體 ID 或主體實體 (PE) ID。此 ID 是 1-50 個字元的特殊字串，印度電信管理局 (TRAI) 提供用來識別您在 TRAI 註冊的實體。
   + **範本 ID** - 傳送簡訊給印度收件人的範本 ID。此 ID 是 TRAI 提供的特殊字串，由 1-50 個字元組成，可識別您向 TRAI 註冊的範本。範本 ID 必須與您為訊息指定的寄件者 ID 相關聯。

   如需傳送簡訊給印度收件人的詳細資訊，請參閱*AWS End User Messaging SMS 《 使用者指南*》中的[印度寄件者 ID 註冊程序](https://docs.aws.amazon.com/sms-voice/latest/userguide/registrations-sms-senderid-india.html)。

1. 選擇 **Publish message** (發佈訊息)。

**提示**  
若要從原始編號傳送 SMS 訊息，您也可以選擇位於 Amazon SNS 主控台導覽面板中的 **來源號碼**。選擇**功能**欄中包含**簡訊**的來源號碼，然後選擇 **Publish text message** (發布簡訊)。

### 傳送訊息 (AWS SDKs)
<a name="sms_publish_sdk"></a>

若要使用其中一個 AWS SDKs 傳送簡訊，請在對應至 Amazon SNS API 中`Publish`請求的開發套件中使用 API 操作。您可以透過此請求，將簡訊直接傳送到電話號碼。您也可以使用 `MessageAttributes` 參數，為下列屬性名稱設定值：

**`AWS.SNS.SMS.SenderID`**  
包含 3-11 個英數字元或連字號 (-) 字元，且至少包括一個字母且無空格的自訂 ID。寄件者 ID 會在接收的裝置上顯示為訊息寄件者。例如，您可以使用您的商業品牌使訊息來源更容易辨識。  
支援依國家或區域而異的寄件者 ID。例如，傳送到美國電話號碼的訊息不會顯示寄件者 ID。如需支援寄件者 IDs的國家或地區清單，請參閱*AWS End User Messaging SMS 《 使用者指南*》中的[使用 傳送簡訊的支援國家和地區 AWS End User Messaging SMS](https://docs.aws.amazon.com/sms-voice/latest/userguide/phone-numbers-sms-by-country.html)。  
如果您未指定寄件者 ID，訊息將顯示[長代碼](https://docs.aws.amazon.com/sms-voice/latest/userguide/phone-numbers-request-long-code.html)做為支援之國家或區域的寄件者 ID。針對要求字母寄件者 ID 的國家或區域，寄件者 ID 會以 *NOTICE* 顯示。  
此訊息層級屬性會覆寫您使用 `SetSMSAttributes` 請求設定的帳戶層級屬性 `DefaultSenderID`。

**`AWS.MM.SMS.OriginationNumber`**  
5-14 個數字的自訂字串，其中可以包含可選的前導加號 (`+`)。此數字字串會在接收裝置上顯示為寄件者的電話號碼。字串必須符合您 AWS 帳戶中為目的地國家/地區設定的起始號碼。來源號碼可以是 10DLC 號碼、免付費號碼、人對人 (P2P) 長碼或短碼。如需詳細資訊，請參閱*AWS End User Messaging SMS 《 使用者指南*》中的[電話號碼](https://docs.aws.amazon.com/sms-voice/latest/userguide/phone-numbers.html)。  
如果您未指定起始號碼，Amazon SNS 會根據 AWS 您的帳戶組態選擇起始號碼。

**`AWS.SNS.SMS.MaxPrice`**  
您願意為傳送簡訊花費的金額上限 (單位為美元)。Amazon SNS 判定若如此做會產生超出最高價的成本，就不會傳送訊息。  
如果您本月至今的簡訊成本已經超出為 `MonthlySpendLimit` 屬性設定的配額，此屬性不會有任何作用。您可以使用屬性 `SetSMSAttributes` 請求設定 `MonthlySpendLimit`。  
若您傳送訊息至 Amazon SNS 主題，每個傳送到各個已訂閱主題電話號碼的訊息都會套用最高價。

**`AWS.SNS.SMS.SMSType`**  
所要傳送訊息的類型：  
+ **`Promotional`** (預設) – 非重要訊息，例如行銷訊息。
+ **`Transactional`**– 支援客戶交易的重要訊息，例如多重要素驗證用的一次性密碼。
此訊息層級屬性會覆寫您使用 `SetSMSAttributes` 請求設定的帳戶層級屬性 `DefaultSMSType`。

**`AWS.MM.SMS.EntityId`**  
此屬性僅適用於傳送簡訊給印度收件人。  
這是您的實體 ID 或主體實體 (PE) 識別碼，用來傳送簡訊給印度收件者。此 ID 是 1-50 個字元的特殊字串，印度電信管理局 (TRAI) 提供用來識別您在 TRAI 註冊的實體。

**`AWS.MM.SMS.TemplateId`**  
此屬性僅適用於傳送簡訊給印度收件人。  
這是傳送簡訊給印度收件人的範本。此 ID 是 TRAI 提供的特殊字串，由 1-50 個字元組成，可識別您向 TRAI 註冊的範本。範本 ID 必須與您為訊息指定的寄件者 ID 相關聯。

#### 傳送訊息
<a name="sms_publish_sdks"></a>

下列程式碼範例示範如何使用 Amazon SNS 發佈簡訊。

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

**適用於 .NET 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](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 的 AWS SDK API 參考*中的[發佈](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Publish)。

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

**適用於 C\$1\$1 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](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 的 AWS SDK API 參考*中的[發佈](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Publish)。

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

**SDK for Java 2.x**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](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 詳細資訊，請參閱 *AWS SDK for Java 2.x API 參考*中的[發佈](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Publish)。

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

**適用於 Kotlin 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](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 詳細資訊，請參閱《適用於 Kotlin 的AWS SDK API 參考》**中的[發佈](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

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

**適用於 PHP 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](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 的 AWS SDK 開發人員指南](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-sending-sms.html#publish-to-a-text-message-sms-message)》。
+  如需 API 詳細資訊，請參閱 *適用於 PHP 的 AWS SDK API 參考*中的[發佈](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/Publish)。

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

**適用於 Python 的 SDK (Boto3)**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](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 詳細資訊，請參閱 *AWS SDK for Python (Boto3) API 參考*中的[發佈](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Publish)。

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

**適用於 SAP ABAP 的開發套件**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](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 詳細資訊，請參閱《適用於 SAP ABAP 的AWS SDK API 參考》**中的[發佈](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------