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

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

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

.NET
Amazon SDK for .NET
提示

要了解如何设置和运行此示例,请参阅 GitHub

using Amazon; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; using System; using System.Threading.Tasks; namespace SNSMessageExample { class SNSMessage { private AmazonSimpleNotificationServiceClient snsClient; /// <summary> /// 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></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

/** * Publish SMS: use 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 */ int main(int argc, char ** argv) { if (argc != 3) { std::cout << "Usage: publish_sms <message_value> <phone_number_value> " << std::endl; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { Aws::SNS::SNSClient sns; Aws::String message = argv[1]; Aws::String phone_number = argv[2]; Aws::SNS::Model::PublishRequest psms_req; psms_req.SetMessage(message); psms_req.SetPhoneNumber(phone_number); auto psms_out = sns.Publish(psms_req); if (psms_out.IsSuccess()) { std::cout << "Message published successfully " << psms_out.GetResult().GetMessageId() << std::endl; } else { std::cout << "Error while publishing message " << psms_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options); return 0; }
  • 有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 Publish

Java
SDK for Java 2.x
提示

要了解如何设置和运行此示例,请参阅 GitHub

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
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

提示

要了解如何设置和运行此示例,请参阅 GitHub

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
SDK for PHP
提示

要了解如何设置和运行此示例,请参阅 GitHub

require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * Sends a 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

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

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