发布到移动电话 - Amazon Simple Notification Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

发布到移动电话

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

注意

如果您想要将一条消息一次发布至多个电话号码,使用电话号码订阅主题会很有用。有关向主题发布 SMS 消息的说明,请参阅 向主题发布

在发送消息时,您可以控制是否对消息进行成本或可靠性传输优化。您还可以指定发件人 ID 或源号码。如果您使用 Amazon SNS API 或 Amazon 开发工具包以编程方式发送消息,则可以指定消息传输的最高价格。

每条 SMS 消息最多能包含 140 字节,字符配额具体取决于编码方案。例如,SMS 消息可以包含:

  • 160 个 GSM 字符

  • 140 个 ASCII 字符

  • 70 个 UCS-2 字符

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

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

发送消息(控制台)

  1. 登录 Amazon SNS 控制台

  2. 在控制台菜单中,选择支持 SMS 消息的 Amazon 区域

  3. 在导航窗格中,选择 Text messaging (SMS)

  4. Mobile text messaging (SMS)(移动文本消息 (SMS))页面上,选择 Publish text message(发布文本消息)。

  5. Publish SMS message(发布 SMS 消息)页面上,对于 Message type(消息类型),选择下列选项之一:

    • Promotional(促销)– 不重要的消息,例如营销消息。

    • Transactional(事务性)– 为客户事务处理提供支持的重要消息,例如多重身份验证的一次性密码。

    注意

    此消息级别的设置会覆盖您的账户级别的默认消息类型。您可以从 Mobile text messaging (SMS)(移动文本消息 (SMS))页面的 Text messaging preferences(文本消息首选项)部分中设置账户级别的默认消息类型。

    有关促销和事务性消息的定价信息,请参阅全球 SMS 定价

  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。

    • 要指定 Origination number(远啊号码),输入一个由 5-14 个数字组成的字符串,以显示为收件人设备上的发件人电话号码。此字符串必须匹配在您 Amazon Web Services 账户 中为目的地国家/地区配置的源号码。起始号码可以是 10DLC 号码、免费电话号码、 person-to-person 长码或短码。有关更多信息,请参阅SMS 消息的源身份

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

  9. 如果您要向位于印度的收件人发送 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 相关联。

    有关向位于印度的收件人发送 SMS 消息的更多信息,请参阅 印度的发送人 ID 注册要求

  10. 选择发布消息

提示

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

发送消息(Amazon 开发工具包)

要使用某个 Amazon 开发工具包发送 SMS 消息,请使用该开发工具包中与 Amazon SNS API 中的 Publish 请求对应的 API 操作。通过此请求,您可以直接向电话号码发送 SMS 消息。您也可使用 MessageAttributes 参数设置以下属性名称的值:

AWS.SNS.SMS.SenderID

包含 3-11 个字母数字字符或连字符 (-) 的自定义 ID,其中包含至少一个字母,并且不能包含空格。该发件人 ID 在接收设备上显示为消息发件人。例如,您可以使用自己的企业品牌让消息来源更易于识别。

各国家或地区对发件人 ID 的支持有所不同。例如,发送至美国电话号码的消息不显示发件人 ID。对于支持发件人 ID 的国家或地区列表,请参阅 支持的国家和区域

如果您未指定发件人 ID,则在支持的国家或地区中长代码会显示为发件人 ID。对于要求使用按字母顺序排列发件人 ID 的国家和地区,NOTICE 显示为发件人 ID。

此消息级别的属性会覆盖您可以通过 SetSMSAttributes 请求设置的账户级别属性 DefaultSenderID

AWS.MM.SMS.OriginationNumber

一个由 5—14 个数字组成的自定义字符串,其中可以包括一个可选的前导加号 (+)。此数字字串在接收设备上显示为发件人的电话号码。此字符串必须匹配在您 Amazon 账户中为目的地国家/地区配置的源号码。发起号码可以是 10DLC 号码、免费电话号码、 person-to-person (P2P) 长码或短码。有关更多信息,请参阅源号码

如果您未指定源号码,Amazon SNS 会根据您的 Amazon 账户配置选择源号码。

AWS.SNS.SMS.MaxPrice

您愿意用于发送 SMS 消息的最高价格(以美元为单位)。如果 Amazon SNS 确定发送消息会产生超出您最高价格的成本,则它不会发送消息。

如果您的 month-to-date SMS 费用已超过为该属性设置的配额,则此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
Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 详细信息,请参阅 Amazon SDK for .NET API 参考中的 Publish

C++
适用于 C++ 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/** * 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 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 Publish

Java
适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 参考中的 Publish

Kotlin
适用于 Kotlin 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 Publish

PHP
适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 参考》中的 Publish