使用 Amazon SNS 將簡訊發佈到行動電話 - Amazon Simple Notification Service

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

使用 Amazon SNS 將簡訊發佈到行動電話

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

注意

如果您想要一次將一個訊息傳送至多個電話號碼,訂閱電話號碼到主題仍然相當實用。如需將簡訊發布至主題的指示,請參閱 將簡訊發佈到 Amazon SNS 主題

傳送訊息時,您可以控制是否針對成本或可靠傳遞將訊息最佳化。您也可以指定寄件者 ID 或來源編號。如果您使用 Amazon SNS API 或 AWS 開發套件以程式設計方式傳送訊息,您可以指定訊息傳遞的最高價格。

每則簡訊最多可包含 140 個位元組,而字元配額則依編碼機制而定。例如,簡訊可包含:

  • 160 個 GSM 字元

  • 140 個 ASCII 字元

  • 70 個 UCS-2 字元

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

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

傳送訊息 (主控台)

  1. 登入 Amazon SNS 主控台

  2. 在主控台功能表中,選擇 AWS 支援簡訊的區域

  3. 在導覽窗格中,選擇 Text messaging (SMS) (簡訊 (SMS))。

  4. Mobile text messaging (SMS) (行動裝置簡訊 (SMS))頁面中,選擇 Publish text message (發布簡訊)。

  5. Publish SMS message (發布簡訊) 頁面上的 Message type (訊息類型) 下,選擇下列其中一個項目:

    • Promotional (促銷) - 非重要訊息,例如行銷訊息。

    • 交易 - 支援客戶交易的重要訊息,例如多重要素驗證用的一次性密碼。

    注意

    此訊息層級設定會覆寫您的帳戶層級預設訊息類型。您可以在 Mobile text messaging (SMS) (行動裝置簡訊 (SMS)) 頁面上的 Text messaging preferences (文字簡訊偏好設定) 區段設定帳戶層級的預設郵件類型。

    如需有關宣傳和交易訊息的定價資訊,請參閱 Worldwide SMS Pricing (全球簡訊定價)。

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

  7. 對於 Message (訊息),請輸入要傳送的訊息。

  8. (選擇性) 在 Origination identities (來源身分) 下,指定如何向收件者識別您的身分:

    • (選用) 若要指定 Sender ID (寄件者 ID),請輸入包含 3-11 個英數字元 (至少包括一個字母且無空格) 的自訂 ID。寄件者 ID 會在接收的裝置上顯示為訊息寄件者。例如,您可以使用您的商業品牌使訊息來源更容易辨識。

      支援依國家和/或區域而異的寄件者 ID。例如,傳送到美國電話號碼的訊息不會顯示寄件者 ID。如需支援寄件者 ID 的國家和區域,請參閱 支援的國家和區域

      如果您未指定寄件者 ID,下列其中一個項目會顯示為來源身分:

      • 在支援長碼的國家/地區,會顯示長碼。

      • 在僅支援寄件者 ID 的國家/地區,會顯示 NOTICE

      此訊息級寄件者 ID 會覆寫您在 Text messaging preferences (簡訊偏好設定) 頁面設定的預設寄件者 ID。

    • 若要指定來源號碼,輸入 5-14 個號碼的字串,以在接收者裝置上顯示為寄件者的電話號碼。此字串必須與您在目的地國家/地區設定 AWS 帳戶 的原始號碼相符。起始號碼可以是 10DLC 號碼、免費電話號碼、 person-to-person 長碼或短碼。如需詳細資訊,請參閱 簡訊的來源身分

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

  9. 如果您要傳送簡訊給印度收件人,請展開 Country-specific attributes (特定國家屬性),並指定下列屬性:

    • 實體 ID - 傳送簡訊給印度收件人的實體 ID 或主體實體 (PE) ID。此 ID 是 1-50 個字元的特殊字串,印度電信管理局 (TRAI) 提供用來識別您在 TRAI 註冊的實體。

    • 範本 ID - 傳送簡訊給印度收件人的範本 ID。此 ID 是 TRAI 提供的特殊字串,由 1-50 個字元組成,可識別您向 TRAI 註冊的範本。範本 ID 必須與您為訊息指定的寄件者 ID 相關聯。

    如需傳送簡訊給印度收件人的詳細資訊,請參閱 印度的寄件者 ID 註冊要求

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

提示

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

傳送訊息 (AWS SDK)

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

AWS.SNS.SMS.SenderID

包含 3-11 個英數字元或連字號 (-) 字元,且至少包括一個字母且無空格的自訂 ID。寄件者 ID 會在接收的裝置上顯示為訊息寄件者。例如,您可以使用您的商業品牌使訊息來源更容易辨識。

支援依國家或區域而異的寄件者 ID。例如,傳送到美國電話號碼的訊息不會顯示寄件者 ID。如需支援寄件者 ID 的國家或區域列表,請參閱 支援的國家和區域

如果您未指定寄件者 ID,訊息將顯示長代碼做為支援之國家或區域的寄件者 ID。針對要求字母寄件者 ID 的國家或區域,寄件者 ID 會以 NOTICE 顯示。

此訊息層級屬性會覆寫您使用 SetSMSAttributes 請求設定的帳戶層級屬性 DefaultSenderID

AWS.MM.SMS.OriginationNumber

5-14 個數字的自訂字串,其中可以包含可選的前導加號 (+)。此數字字串會在接收裝置上顯示為寄件者的電話號碼。字串必須符合您 AWS 帳戶中針對目的地國家/地區設定的原始編號。起始號碼可以是 10DLC 號碼、免費電話號碼、 person-to-person (P2P) 長碼或短碼。如需詳細資訊,請參閱 來源號碼

如果您未指定起始編號,Amazon SNS 會根據您的 AWS 帳戶組態選擇一個起始編號。

AWS.SNS.SMS.MaxPrice

您願意為傳送簡訊花費的金額上限 (單位為美元)。Amazon SNS 判定若如此做會產生超出最高價的成本,就不會傳送訊息。

如果您的 month-to-date SMS 成本已經超過為屬性設定的配額,則此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 相關聯。

傳送訊息

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

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 詳細資訊,請參閱 AWS SDK for .NET API 參考中的發佈

C++
適用於 C++ 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/** * 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 詳細資訊,請參閱 AWS SDK for C++ API 參考中的發佈

Java
適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 參考中的發佈

Kotlin
適用於 Kotlin 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

suspend fun pubTextSMS( messageVal: String?, phoneNumberVal: String?, ) { val request = PublishRequest { message = messageVal phoneNumber = phoneNumberVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println("${result.messageId} message sent.") } }
  • 如需 API 詳細資訊,請參閱《適用於 Kotlin 的AWS SDK API 參考》中的發佈

PHP
適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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()); }
Python
適用於 Python (Boto3) 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 參考中的發佈