使用软件开发工具包发布 Amazon SNS 短信 Amazon - Amazon Simple Notification Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

使用软件开发工具包发布 Amazon SNS 短信 Amazon

以下代码示例演示了如何使用 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++
SDK for C++
注意

还有更多相关信息 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
SDK for Python (Boto3)
注意

还有更多相关信息 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

有关 S Amazon DK 开发者指南和代码示例的完整列表,请参阅将 Amazon SNS 与 Amazon 开发工具包结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。