Invio di messaggi SMS - Amazon Pinpoint

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Invio di messaggi SMS

È possibile utilizzare l'API Amazon Pinpoint per inviare messaggi SMS (messaggi di testo) a ID degli endpoint e numeri di telefono specifici. Questa sezione contiene esempi di codice completo che puoi usare per inviare messaggi SMS tramite l'API Amazon Pinpoint utilizzando AWS SDK.

C#

Utilizza questo esempio per inviare un messaggio SMS tramite l'AWS SDK for .NET. Questo esempio si basa sul presupposto che l'AWS SDK for .NET sia già stato installato e configurato. Per ulteriori informazioni, consulta l'argomento relativo alle nozioni di base nella Guida per gli sviluppatori di AWS SDK for .NET.

Questo esempio presuppone che tu stia utilizzando un file di credenziali condivise per specificare la chiave di accesso e la chiave di accesso segreta per un utente IAM esistente. Per ulteriori informazioni, consulta l'argomento relativo alla configurazione delle credenziali AWS nella Guida per gli sviluppatori di AWS SDK for .NET.

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

Utilizza questo esempio per inviare un messaggio SMS tramite l'AWS SDK for Java. In questo esempio si presume che SDK per Java sia già stato installato e configurato. Per ulteriori informazioni, consulta l'argomento relativo alle nozioni di base nella Guida per gli sviluppatori di AWS SDK for Java.

Questo esempio presuppone che tu stia utilizzando un file di credenziali condivise per specificare la chiave di accesso e la chiave di accesso segreta per un utente IAM esistente. Per ulteriori informazioni, consulta l'argomento relativo alla configurazione della regione e delle credenziali predefinite nella Guida per gli sviluppatori di 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); } } }

Per l'esempio completo dell'SDK, consulta SendMessage.java su GitHub.

JavaScript (Node.js)

Utilizza questo esempio per inviare un messaggio SMS utilizzando AWS SDK per JavaScript in Node.js. In questo esempio si presume che SDK per JavaScript in Node.js sia già stato installato e configurato. Per ulteriori informazioni, consulta Nozioni di base nella Guida per gli sviluppatori di Node.js per AWS SDK per JavaScript.

Questo esempio presuppone che tu stia utilizzando un file di credenziali condivise per specificare la chiave di accesso e la chiave di accesso segreta per un utente IAM esistente. Per ulteriori informazioni consulta Impostazione delle credenziali nella Guida per gli sviluppatori di AWS SDK per JavaScript in Node.js.

"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

Utilizza questo esempio per inviare un messaggio SMS tramite l'AWS SDK for Python (Boto3). Questo esempio si basa sul presupposto che SDK per Python sia già stato installato e configurato. Per ulteriori informazioni, consulta Quickstart nella Guida introduttiva di AWS SDK per Python (Boto3).

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()

È inoltre possibile utilizzare modelli di messaggi per inviare messaggi SMS, come illustrato nell'esempio seguente:

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()

Questi esempi presuppongono che tu stia utilizzando un file di credenziali condivise per specificare la chiave di accesso e la chiave di accesso segreta per un utente IAM esistente. Per informazioni dettagliate, consulta Credentials nella documentazione di riferimento delle API AWS SDK per Python (Boto3).