기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
SMS 메시지 보내기
Amazon Pinpoint API를 사용하여 특정 전화번호 또는 엔드포인트 ID에 SMS 메시지(문자 메시지)를 보낼 수 있습니다. 이 단원에는 AWS SDK를 사용하여 Amazon Pinpoint API를 통해 SMS 메시지를 보낼 때 사용할 수 있는 전체 코드 예제가 나와 있습니다.
- C#
-
이 예제를 사용하여 AWS SDK for .NET
를 사용해 SMS 메시지를 보냅니다. 이 예제에서는 AWS SDK for .NET를 이미 설치 및 구성했다고 가정합니다. 자세한 내용은 AWS SDK for .NET 개발자 안내서의 시작하기를 참조하세요. 이 예제에서는 공유 자격 증명 파일을 사용하여 기존 IAM 사용자의 액세스 키 및 보안 액세스 키를 지정한다고 가정합니다. 자세한 내용은 AWS SDK for .NET 개발자 안내서의 AWS 보안 인증 정보 구성을 참조하세요.
using System; using System.Collections.Generic; using Amazon; using Amazon.Pinpoint; using Amazon.Pinpoint.Model; namespace SendMessage { class MainClass { // The AWS Region that you want to use to send the message. For a list of // AWS Regions where the Amazon Pinpoint API is available, see // https://docs.aws.amazon.com/pinpoint/latest/apireference/ private static readonly string region = "us-east-1"; // The phone number or short code to send the message from. The phone number // or short code that you specify has to be associated with your Amazon Pinpoint // account. For best results, specify long codes in E.164 format. private static readonly string originationNumber = "+12065550199"; // The recipient's phone number. For best results, you should specify the // phone number in E.164 format. private static readonly string destinationNumber = "+14255550142"; // The content of the SMS message. private static readonly string message = "This message was sent through Amazon Pinpoint" + "using the AWS SDK for .NET. Reply STOP to opt out."; // The Pinpoint project/application ID to use when you send this message. // Make sure that the SMS channel is enabled for the project or application // that you choose. private static readonly string appId = "ce796be37f32f178af652b26eexample"; // The type of SMS message that you want to send. If you plan to send // time-sensitive content, specify TRANSACTIONAL. If you plan to send // marketing-related content, specify PROMOTIONAL. private static readonly string messageType = "TRANSACTIONAL"; // The registered keyword associated with the originating short code. private static readonly string registeredKeyword = "myKeyword"; // The sender ID to use when sending the message. Support for sender ID // varies by country or region. For more information, see // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html private static readonly string senderId = "mySenderId"; public static void Main(string[] args) { using (AmazonPinpointClient client = new AmazonPinpointClient(RegionEndpoint.GetBySystemName(region))) { SendMessagesRequest sendRequest = new SendMessagesRequest { ApplicationId = appId, MessageRequest = new MessageRequest { Addresses = new Dictionary<string, AddressConfiguration> { { destinationNumber, new AddressConfiguration { ChannelType = "SMS" } } }, MessageConfiguration = new DirectMessageConfiguration { SMSMessage = new SMSMessage { Body = message, MessageType = messageType, OriginationNumber = originationNumber, SenderId = senderId, Keyword = registeredKeyword } } } }; try { Console.WriteLine("Sending message..."); SendMessagesResponse response = client.SendMessages(sendRequest); Console.WriteLine("Message sent!"); } catch (Exception ex) { Console.WriteLine("The message wasn't sent. Error message: " + ex.Message); } } } } }
- Java
-
이 예제를 사용하여 AWS SDK for Java
를 사용해 SMS 메시지를 보냅니다. 이 예제에서는 Java용 SDK를 이미 설치 및 구성했다고 가정합니다. 자세한 내용은 AWS SDK for Java 개발자 안내서의 시작하기를 참조하세요. 이 예제에서는 공유 자격 증명 파일을 사용하여 기존 IAM 사용자의 액세스 키 및 보안 액세스 키를 지정한다고 가정합니다. 자세한 내용은 AWS SDK for Java 개발자 안내서의 기본 보안 인증 정보 및 리전 설정을 참조하세요.
import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration; import software.amazon.awssdk.services.pinpoint.model.SMSMessage; import software.amazon.awssdk.services.pinpoint.model.AddressConfiguration; import software.amazon.awssdk.services.pinpoint.model.ChannelType; import software.amazon.awssdk.services.pinpoint.model.MessageRequest; import software.amazon.awssdk.services.pinpoint.model.SendMessagesRequest; import software.amazon.awssdk.services.pinpoint.model.SendMessagesResponse; import software.amazon.awssdk.services.pinpoint.model.MessageResponse; import software.amazon.awssdk.services.pinpoint.model.PinpointException; import java.util.HashMap; import java.util.Map;
import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration; import software.amazon.awssdk.services.pinpoint.model.SMSMessage; import software.amazon.awssdk.services.pinpoint.model.AddressConfiguration; import software.amazon.awssdk.services.pinpoint.model.ChannelType; import software.amazon.awssdk.services.pinpoint.model.MessageRequest; import software.amazon.awssdk.services.pinpoint.model.SendMessagesRequest; import software.amazon.awssdk.services.pinpoint.model.SendMessagesResponse; import software.amazon.awssdk.services.pinpoint.model.MessageResponse; import software.amazon.awssdk.services.pinpoint.model.PinpointException; import java.util.HashMap; import java.util.Map; /** * 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 SendMessage { // The type of SMS message that you want to send. If you plan to send // time-sensitive content, specify TRANSACTIONAL. If you plan to send // marketing-related content, specify PROMOTIONAL. public static String messageType = "TRANSACTIONAL"; // The registered keyword associated with the originating short code. public static String registeredKeyword = "myKeyword"; // The sender ID to use when sending the message. Support for sender ID // varies by country or region. For more information, see // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html public static String senderId = "MySenderID"; public static void main(String[] args) { final String usage = """ Usage: <message> <appId> <originationNumber> <destinationNumber>\s Where: message - The body of the message to send. appId - The Amazon Pinpoint project/application ID to use when you send this message. originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s """; if (args.length != 4) { System.out.println(usage); System.exit(1); } String message = args[0]; String appId = args[1]; String originationNumber = args[2]; String destinationNumber = args[3]; System.out.println("Sending a message"); PinpointClient pinpoint = PinpointClient.builder() .region(Region.US_EAST_1) .build(); sendSMSMessage(pinpoint, message, appId, originationNumber, destinationNumber); pinpoint.close(); } public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId, String originationNumber, String destinationNumber) { try { Map<String, AddressConfiguration> addressMap = new HashMap<String, AddressConfiguration>(); AddressConfiguration addConfig = AddressConfiguration.builder() .channelType(ChannelType.SMS) .build(); addressMap.put(destinationNumber, addConfig); SMSMessage smsMessage = SMSMessage.builder() .body(message) .messageType(messageType) .originationNumber(originationNumber) .senderId(senderId) .keyword(registeredKeyword) .build(); // Create a DirectMessageConfiguration object. DirectMessageConfiguration direct = DirectMessageConfiguration.builder() .smsMessage(smsMessage) .build(); MessageRequest msgReq = MessageRequest.builder() .addresses(addressMap) .messageConfiguration(direct) .build(); // create a SendMessagesRequest object SendMessagesRequest request = SendMessagesRequest.builder() .applicationId(appId) .messageRequest(msgReq) .build(); SendMessagesResponse response = pinpoint.sendMessages(request); MessageResponse msg1 = response.messageResponse(); Map map1 = msg1.result(); // Write out the result of sendMessage. map1.forEach((k, v) -> System.out.println((k + ":" + v))); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
전체 SDK 예제를 보려면 GitHub
에서 SendMessage.java 를 참조하세요. - JavaScript (Node.js)
-
Node.js의 JavaScript용 AWS SDK
를 사용하여 SMS 메시지를 보내려면 이 예제를 사용하세요. 이 예제에서는 Node.js의 JavaScript용 SDK를 이미 설치 및 구성했다고 가정합니다. 자세한 내용은 Node.js의 JavaScript용 AWS SDK 개발자 설명서의 시작하기를 참조하세요. 이 예제에서는 공유 자격 증명 파일을 사용하여 기존 IAM 사용자의 액세스 키 및 보안 액세스 키를 지정한다고 가정합니다. 자세한 내용은 Node.js의 JavaScript용 AWS SDK 개발자 설명서의 보안 인증 정보 설정을 참조하세요.
"use strict"; var AWS = require("aws-sdk"); // The AWS Region that you want to use to send the message. For a list of // AWS Regions where the Amazon Pinpoint API is available, see // https://docs.aws.amazon.com/pinpoint/latest/apireference/. var aws_region = "us-east-1"; // The phone number or short code to send the message from. The phone number // or short code that you specify has to be associated with your Amazon Pinpoint // account. For best results, specify long codes in E.164 format. var originationNumber = "+12065550199"; // The recipient's phone number. For best results, you should specify the // phone number in E.164 format. var destinationNumber = "+14255550142"; // The content of the SMS message. var message = "This message was sent through Amazon Pinpoint " + "using the AWS SDK for JavaScript in Node.js. Reply STOP to " + "opt out."; // The Amazon Pinpoint project/application ID to use when you send this message. // Make sure that the SMS channel is enabled for the project or application // that you choose. var applicationId = "ce796be37f32f178af652b26eexample"; // The type of SMS message that you want to send. If you plan to send // time-sensitive content, specify TRANSACTIONAL. If you plan to send // marketing-related content, specify PROMOTIONAL. var messageType = "TRANSACTIONAL"; // The registered keyword associated with the originating short code. var registeredKeyword = "myKeyword"; // The sender ID to use when sending the message. Support for sender ID // varies by country or region. For more information, see // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html var senderId = "MySenderID"; // Specify that you're using a shared credentials file, and optionally specify // the profile that you want to use. var credentials = new AWS.SharedIniFileCredentials({ profile: "default" }); AWS.config.credentials = credentials; // Specify the region. AWS.config.update({ region: aws_region }); //Create a new Pinpoint object. var pinpoint = new AWS.Pinpoint(); // Specify the parameters to pass to the API. var params = { ApplicationId: applicationId, MessageRequest: { Addresses: { [destinationNumber]: { ChannelType: "SMS", }, }, MessageConfiguration: { SMSMessage: { Body: message, Keyword: registeredKeyword, MessageType: messageType, OriginationNumber: originationNumber, SenderId: senderId, }, }, }, }; //Try to send the message. pinpoint.sendMessages(params, function (err, data) { // If something goes wrong, print an error message. if (err) { console.log(err.message); // Otherwise, show the unique ID for the message. } else { console.log( "Message sent! " + data["MessageResponse"]["Result"][destinationNumber]["StatusMessage"] ); } });
- Python
-
이 예제를 사용하여 AWS SDK for Python (Boto3)
를 사용해 SMS 메시지를 보냅니다. 이 예제에서는 Python용 SDK를 이미 설치 및 구성했다고 가정합니다. 자세한 내용은 Python용 AWS SDK(Boto3) 시작하기의 Quickstart 를 참조하세요. import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) def send_sms_message( pinpoint_client, app_id, origination_number, destination_number, message, message_type, ): """ Sends an SMS message with Amazon Pinpoint. :param pinpoint_client: A Boto3 Pinpoint client. :param app_id: The Amazon Pinpoint project/application ID to use when you send this message. The SMS channel must be enabled for the project or application. :param destination_number: The recipient's phone number in E.164 format. :param origination_number: The phone number to send the message from. This phone number must be associated with your Amazon Pinpoint account and be in E.164 format. :param message: The content of the SMS message. :param message_type: The type of SMS message that you want to send. If you send time-sensitive content, specify TRANSACTIONAL. If you send marketing-related content, specify PROMOTIONAL. :return: The ID of the message. """ try: response = pinpoint_client.send_messages( ApplicationId=app_id, MessageRequest={ "Addresses": {destination_number: {"ChannelType": "SMS"}}, "MessageConfiguration": { "SMSMessage": { "Body": message, "MessageType": message_type, "OriginationNumber": origination_number, } }, }, ) except ClientError: logger.exception("Couldn't send message.") raise else: return response["MessageResponse"]["Result"][destination_number]["MessageId"] def main(): app_id = "ce796be37f32f178af652b26eexample" origination_number = "+12065550199" destination_number = "+14255550142" message = ( "This is a sample message sent from Amazon Pinpoint by using the AWS SDK for " "Python (Boto 3)." ) message_type = "TRANSACTIONAL" print("Sending SMS message.") message_id = send_sms_message( boto3.client("pinpoint"), app_id, origination_number, destination_number, message, message_type, ) print(f"Message sent! Message ID: {message_id}.") if __name__ == "__main__": main()
또한 다음 예제와 같이 메시지 템플릿을 사용하여 SMS 메시지를 보낼 수도 있습니다.
import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) def send_templated_sms_message( pinpoint_client, project_id, destination_number, message_type, origination_number, template_name, template_version, ): """ Sends an SMS message to a specific phone number using a pre-defined template. :param pinpoint_client: A Boto3 Pinpoint client. :param project_id: An Amazon Pinpoint project (application) ID. :param destination_number: The phone number to send the message to. :param message_type: The type of SMS message (promotional or transactional). :param origination_number: The phone number that the message is sent from. :param template_name: The name of the SMS template to use when sending the message. :param template_version: The version number of the message template. :return The ID of the message. """ try: response = pinpoint_client.send_messages( ApplicationId=project_id, MessageRequest={ "Addresses": {destination_number: {"ChannelType": "SMS"}}, "MessageConfiguration": { "SMSMessage": { "MessageType": message_type, "OriginationNumber": origination_number, } }, "TemplateConfiguration": { "SMSTemplate": {"Name": template_name, "Version": template_version} }, }, ) except ClientError: logger.exception("Couldn't send message.") raise else: return response["MessageResponse"]["Result"][destination_number]["MessageId"] def main(): region = "us-east-1" origination_number = "+18555550001" destination_number = "+14255550142" project_id = "7353f53e6885409fa32d07cedexample" message_type = "TRANSACTIONAL" template_name = "My_SMS_Template" template_version = "1" message_id = send_templated_sms_message( boto3.client("pinpoint", region_name=region), project_id, destination_number, message_type, origination_number, template_name, template_version, ) print(f"Message sent! Message ID: {message_id}.") if __name__ == "__main__": main()
이들 예제에서는 공유 보안 인증 정보 파일을 사용하여 기존 IAM 사용자의 액세스 키 및 비밀 액세스 키를 지정한다고 가정합니다. 자세한 내용은 Python용 AWS SDK(Boto3) API 참조의 보안 인증 정보
를 참조하세요.