

**Hinweis zum Ende des Supports:** Am 30. Oktober 2026 AWS wird der Support für Amazon Pinpoint eingestellt. Nach dem 30. Oktober 2026 können Sie nicht mehr auf die Amazon-Pinpoint-Konsole oder die Amazon-Pinpoint-Ressourcen (Endpunkte, Segmente, Kampagnen, Journeys und Analytik) zugreifen. Weitere Informationen finden Sie unter [Ende des Amazon-Pinpoint-Supports](https://docs.aws.amazon.com/console/pinpoint/migration-guide). **Hinweis:** APIs In Bezug auf SMS sind Sprach-, mobile Push-, OTP- und Telefonnummernvalidierung von dieser Änderung nicht betroffen und werden von AWS End User Messaging unterstützt.

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Senden Sie Transaktionsnachrichten von Ihrer App aus mit Amazon Pinpoint
<a name="send-messages"></a>

Sie können die Amazon Pinpoint API und die verwenden AWS SDKs , um *Transaktionsnachrichten* direkt von Ihrer App aus zu senden. Transaktionsnachrichten sind Nachrichten, die Sie an bestimmte Empfänger senden – im Gegensatz zu Nachrichten, die Sie an Segmente senden. Es gibt mehrere Gründe, warum Sie möglicherweise Transaktionsnachrichten senden möchten anstatt kampagnenbasierte Nachrichten. Sie könnten z. B. eine Auftragsbestätigung per E-Mail senden, wenn ein Kunde eine Bestellung aufgibt. Sie könnten per SMS- oder Sprachnachricht auch ein einmaliges Passwort senden, mit dem ein Kunde die Erstellung seines Kontos für Ihren Service abschließen kann.

Dieser Abschnitt enthält Codebeispiele in mehreren Programmiersprachen, die Sie verwenden können, um Transaktionsnachrichten, SMS-Nachrichten und Sprachnachrichten zu versenden.

[Weitere Codebeispiele zu Endpunkten, Segmenten und Kanälen finden Sie unter Codebeispiele.](https://docs.aws.amazon.com/pinpoint/latest/developerguide/service_code_examples.html)

**Topics**
+ [Senden Sie Transaktions-E-Mails mit Amazon Pinpoint](send-messages-email.md)
+ [Senden Sie Transaktions-SMS-Nachrichten mit Amazon Pinpoint](send-messages-sms.md)
+ [Senden Sie Sprachnachrichten mit Amazon Pinpoint](send-messages-voice.md)

# Senden Sie Transaktions-E-Mails mit Amazon Pinpoint
<a name="send-messages-email"></a>

Dieser Abschnitt enthält umfassende Codebeispiele, die Sie verwenden können, um E-Mail-Transaktionsnachrichten über Amazon Pinpoint zu versenden.
+ [Mithilfe des SendMessages Vorgangs in der Amazon Pinpoint-API](send-messages-sdk.md): Sie können den `SendMessages` Vorgang in der Amazon Pinpoint Pinpoint-API verwenden, um Nachrichten in allen Kanälen zu senden, die Amazon Pinpoint unterstützt, einschließlich der Kanäle für Push-Benachrichtigungen, SMS, Sprach- und E-Mail-Kanäle.

  Der Vorteil dieser Operation besteht darin, dass die Anforderungssyntax zum Senden von Nachrichten in allen Kanälen sehr ähnlich ist. So ist es einfacher, vorhandenen Code wiederzuverwenden. Mit diesem `SendMessages` Vorgang können Sie auch Inhalte in Ihren E-Mail-Nachrichten ersetzen und E-Mails an den Amazon Pinpoint-Endpunkt IDs statt an bestimmte E-Mail-Adressen senden.

Dieser Abschnitt enthält Codebeispiele in mehreren Programmiersprachen, die Sie verwenden können, um E-Mail-Transaktionsnachrichten zu versenden.

Weitere Codebeispiele für Endpunkte, Segmente und Kanäle finden Sie unter [Codebeispiele](https://docs.aws.amazon.com/pinpoint/latest/developerguide/service_code_examples.html).

## Wählen Sie eine Methode zum Senden von E-Mails
<a name="send-messages-email-choose-method"></a>

Die beste Methode für den Versand von E-Mail-Transaktionsnachrichten hängt vom jeweiligen Anwendungsszenario ab. Wenn Sie beispielsweise E-Mails mithilfe einer Drittanbieteranwendung senden müssen oder wenn für Ihre Programmiersprache kein AWS SDK verfügbar ist, müssen Sie möglicherweise die SMTP-Schnittstelle verwenden. Wenn Sie Nachrichten in anderen Kanälen senden möchten, die von Amazon Pinpoint unterstützt werden, und für diese Anforderungen einen konsistenten Code anwenden wollen, sollten Sie die Operation `SendMessages` in der Amazon-Pinpoint-API verwenden.

## Wählen Sie zwischen Amazon Pinpoint und Amazon SES
<a name="send-email-ses"></a>

Wenn Sie eine große Anzahl von Transaktions-E-Mails senden, z. B. Kaufbestätigungen oder Nachrichten zum Zurücksetzen des Passworts, sollten Sie Amazon SES verwenden. Amazon SES verfügt über eine API und eine SMTP-Schnittstelle, die beide gut geeignet sind, um E-Mails von Ihren Anwendungen oder Services zu senden. Es bietet auch zusätzliche E-Mail-Funktionen, einschließlich E-Mail-Empfangsfunktionen, Konfigurationssets und Sendeautorisierungsfunktionen.

Amazon SES enthält auch eine SMTP-Schnittstelle, die Sie in Ihre vorhandenen Drittanbieteranwendungen integrieren können, einschließlich CRM-Services (Customer Relationship Management) wie Salesforce. Weitere Informationen zum Senden von E-Mails mit Amazon SES finden Sie im [Amazon Simple Email Service Entwicklerhandbuch](https://docs.aws.amazon.com/ses/latest/dg/Welcome.html).

# Senden von E-Mails mithilfe der Amazon-Pinpoint-API
<a name="send-messages-sdk"></a>

Dieser Abschnitt enthält vollständige Codebeispiele, die Sie verwenden können, um E-Mails mithilfe eines AWS SDK über die Amazon Pinpoint Pinpoint-API zu versenden. Sie müssen entweder eine E-Mail-Adresse oder eine Domain verifiziert haben, bevor Sie eine Nachricht senden können.

------
#### [ C\$1 ]

Verwenden Sie dieses Beispiel, um eine E-Mail mithilfe des [AWS SDK für .NET](https://aws.amazon.com/sdk-for-net/) zu versenden. Bei diesem Beispiel wird vorausgesetzt, dass Sie das SDK für .NET bereits installiert und konfiguriert haben. Weitere Informationen finden Sie unter [Erste Schritte mit AWS SDK für .NET](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config.html) im *AWS SDK für .NET -Entwicklerhandbuch*.

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen Benutzer anzugeben. Weitere Informationen finden Sie unter [Konfiguration von AWS Anmeldeinformationen](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/creds-idc.html) im *AWS SDK für .NET Entwicklerhandbuch*.

Dieses Codebeispiel wurde mit der AWS SDK für .NET Version 3.3.29.13 und.NET Core Runtime Version 2.1.2 getestet.

```
using Amazon;
using Amazon.Pinpoint;
using Amazon.Pinpoint.Model;
using Microsoft.Extensions.Configuration;

namespace SendEmailMessage;

public class SendEmailMainClass
{
    public static async Task Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("settings.json") // Load test settings from .json file.
        .AddJsonFile("settings.local.json",
            true) // Optionally load local settings.
        .Build();

        // The AWS Region that you want to use to send the email. For a list of
        // AWS Regions where the Amazon Pinpoint API is available, see 
        // https://docs.aws.amazon.com/pinpoint/latest/apireference/
        string region = "us-east-1";

        // The "From" address. This address has to be verified in Amazon Pinpoint 
        // in the region you're using to send email.
        string senderAddress = configuration["SenderAddress"]!;

        // The address on the "To" line. If your Amazon Pinpoint account is in
        // the sandbox, this address also has to be verified. 
        string toAddress = configuration["ToAddress"]!;

        // 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.
        string appId = configuration["AppId"]!;

        try
        {
            await SendEmailMessage(region, appId, toAddress, senderAddress);
        }
        catch (Exception ex)
        {
            Console.WriteLine("The message wasn't sent. Error message: " + ex.Message);
        }
    }

    public static async Task<MessageResponse> SendEmailMessage(
        string region, string appId, string toAddress, string senderAddress)
    {
        var client = new AmazonPinpointClient(RegionEndpoint.GetBySystemName(region));

        // The subject line of the email.
        string subject = "Amazon Pinpoint Email test";

        // The body of the email for recipients whose email clients don't 
        // support HTML content.
        string textBody = @"Amazon Pinpoint Email Test (.NET)"
                          + "\n---------------------------------"
                          + "\nThis email was sent using the Amazon Pinpoint API using the AWS SDK for .NET.";

        // The body of the email for recipients whose email clients support
        // HTML content.
        string htmlBody = @"<html>"
                          + "\n<head></head>"
                          + "\n<body>"
                          + "\n  <h1>Amazon Pinpoint Email Test (AWS SDK for .NET)</h1>"
                          + "\n  <p>This email was sent using the "
                          + "\n    <a href='https://aws.amazon.com/pinpoint/'>Amazon Pinpoint</a> API "
                          + "\n    using the <a href='https://aws.amazon.com/sdk-for-net/'>AWS SDK for .NET</a>"
                          + "\n  </p>"
                          + "\n</body>"
                          + "\n</html>";

        // The character encoding the you want to use for the subject line and
        // message body of the email.
        string charset = "UTF-8";

        var sendRequest = new SendMessagesRequest
        {
            ApplicationId = appId,
            MessageRequest = new MessageRequest
            {
                Addresses = new Dictionary<string, AddressConfiguration>
                {
                    {
                        toAddress,
                        new AddressConfiguration
                        {
                            ChannelType = ChannelType.EMAIL
                        }
                    }
                },
                MessageConfiguration = new DirectMessageConfiguration
                {
                    EmailMessage = new EmailMessage
                    {
                        FromAddress = senderAddress,
                        SimpleEmail = new SimpleEmail
                        {
                            HtmlPart = new SimpleEmailPart
                            {
                                Charset = charset,
                                Data = htmlBody
                            },
                            TextPart = new SimpleEmailPart
                            {
                                Charset = charset,
                                Data = textBody
                            },
                            Subject = new SimpleEmailPart
                            {
                                Charset = charset,
                                Data = subject
                            }
                        }
                    }
                }
            }
        };
        Console.WriteLine("Sending message...");
        SendMessagesResponse response = await client.SendMessagesAsync(sendRequest);
        Console.WriteLine("Message sent!");
        return response.MessageResponse;
    }
}
```

------
#### [ Java ]

Verwenden Sie dieses Beispiel, um eine E-Mail mithilfe des [AWS SDK für Java](https://aws.amazon.com/sdk-for-java/) zu versenden. Bei diesem Beispiel wird vorausgesetzt, dass Sie das AWS SDK for Java 2.x bereits installiert und konfiguriert haben. Weitere Informationen finden Sie unter [Erste Schritte](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html) im *AWS SDK for Java 2.x -Entwicklerhandbuch*.

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen Benutzer anzugeben. Weitere Informationen finden Sie unter [Einrichten der Standard-Anmeldeinformationen und ‑Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html#setup-credentials) im *AWS SDK für Java -Entwicklerhandbuch*.

Dieses Codebeispiel wurde mit der AWS SDK für Java Version 2.3.1 und der OpenJDK-Version 11.0.1 getestet.

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.AddressConfiguration;
import software.amazon.awssdk.services.pinpoint.model.ChannelType;
import software.amazon.awssdk.services.pinpoint.model.SimpleEmailPart;
import software.amazon.awssdk.services.pinpoint.model.SimpleEmail;
import software.amazon.awssdk.services.pinpoint.model.EmailMessage;
import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration;
import software.amazon.awssdk.services.pinpoint.model.MessageRequest;
import software.amazon.awssdk.services.pinpoint.model.SendMessagesRequest;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import software.amazon.awssdk.services.pinpointemail.PinpointEmailClient;
import software.amazon.awssdk.services.pinpointemail.model.Body;
import software.amazon.awssdk.services.pinpointemail.model.Content;
import software.amazon.awssdk.services.pinpointemail.model.Destination;
import software.amazon.awssdk.services.pinpointemail.model.EmailContent;
import software.amazon.awssdk.services.pinpointemail.model.Message;
import software.amazon.awssdk.services.pinpointemail.model.SendEmailRequest;

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.AddressConfiguration;
import software.amazon.awssdk.services.pinpoint.model.ChannelType;
import software.amazon.awssdk.services.pinpoint.model.SimpleEmailPart;
import software.amazon.awssdk.services.pinpoint.model.SimpleEmail;
import software.amazon.awssdk.services.pinpoint.model.EmailMessage;
import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration;
import software.amazon.awssdk.services.pinpoint.model.MessageRequest;
import software.amazon.awssdk.services.pinpoint.model.SendMessagesRequest;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import software.amazon.awssdk.services.pinpointemail.PinpointEmailClient;
import software.amazon.awssdk.services.pinpointemail.model.Body;
import software.amazon.awssdk.services.pinpointemail.model.Content;
import software.amazon.awssdk.services.pinpointemail.model.Destination;
import software.amazon.awssdk.services.pinpointemail.model.EmailContent;
import software.amazon.awssdk.services.pinpointemail.model.Message;
import software.amazon.awssdk.services.pinpointemail.model.SendEmailRequest;

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 SendEmailMessage {

        // The character encoding the you want to use for the subject line and
        // message body of the email.
        public static String charset = "UTF-8";

    // The body of the email for recipients whose email clients support HTML content.
    static final String body = """
        Amazon Pinpoint test (AWS SDK for Java 2.x)
                
        This email was sent through the Amazon Pinpoint Email API using the AWS SDK for Java 2.x
                
        """;

        public static void main(String[] args) {
                final String usage = """

                                Usage:    <subject> <appId> <senderAddress> <toAddress>

            Where:
               subject - The email subject to use.
               senderAddress - The from address. This address has to be verified in Amazon Pinpoint in the region you're using to send email\s
               toAddress - The to address. This address has to be verified in Amazon Pinpoint in the region you're using to send email\s
            """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String subject = args[0];
        String senderAddress = args[1];
        String toAddress = args[2];
        System.out.println("Sending a message");
        PinpointEmailClient pinpoint = PinpointEmailClient.builder()
            .region(Region.US_EAST_1)
            .build();

        sendEmail(pinpoint, subject, senderAddress, toAddress);
        System.out.println("Email was sent");
        pinpoint.close();
    }

    public static void sendEmail(PinpointEmailClient pinpointEmailClient, String subject, String senderAddress, String toAddress) {
        try {
            Content content = Content.builder()
                .data(body)
                .build();

            Body messageBody = Body.builder()
                .text(content)
                .build();

            Message message = Message.builder()
                .body(messageBody)
                .subject(Content.builder().data(subject).build())
                .build();

            Destination destination = Destination.builder()
                .toAddresses(toAddress)
                .build();

            EmailContent emailContent = EmailContent.builder()
                .simple(message)
                .build();

            SendEmailRequest sendEmailRequest = SendEmailRequest.builder()
                .fromEmailAddress(senderAddress)
                .destination(destination)
                .content(emailContent)
                .build();

            pinpointEmailClient.sendEmail(sendEmailRequest);
            System.out.println("Message Sent");

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```

[Das vollständige SDK-Beispiel finden Sie unter .java on. SendEmailMessage [GitHub](https://github.com/)](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendEmailMessage.java)

------
#### [ JavaScript (Node.js) ]

Verwenden Sie dieses Beispiel, um E-Mails mithilfe des [AWS SDK für JavaScript in Node.js](https://aws.amazon.com/sdk-for-javascript/) zu senden. In diesem Beispiel wird vorausgesetzt, dass Sie das SDK für JavaScript in Node.js bereits installiert und konfiguriert haben. Weitere Informationen finden Sie unter [Erste Schritte](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-nodejs.html) im *AWS SDK für JavaScript im Node.js Developer Guide*.

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen Benutzer anzugeben. Weitere Informationen finden Sie unter [Einrichten von Anmeldeinformationen](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials.html) im *AWS SDK für JavaScript im Node.js Developer Guide*.

Dieses Codebeispiel wurde mit dem SDK für JavaScript in Node.js Version 2.388.0 und Node.js Version 11.7.0 getestet.

```
"use strict";

const AWS = require("aws-sdk");

// The AWS Region that you want to use to send the email. For a list of
// AWS Regions where the Amazon Pinpoint API is available, see
// https://docs.aws.amazon.com/pinpoint/latest/apireference/
const aws_region = "us-west-2";

// The "From" address. This address has to be verified in Amazon Pinpoint
// in the region that you use to send email.
const senderAddress = "sender@example.com";

// The address on the "To" line. If your Amazon Pinpoint account is in
// the sandbox, this address also has to be verified.
var toAddress = "recipient@example.com";

// 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.
const appId = "ce796be37f32f178af652b26eexample";

// The subject line of the email.
var subject = "Amazon Pinpoint (AWS SDK for JavaScript in Node.js)";

// The email body for recipients with non-HTML email clients.
var body_text = `Amazon Pinpoint Test (SDK for JavaScript in Node.js)
----------------------------------------------------
This email was sent with Amazon Pinpoint using the AWS SDK for JavaScript in Node.js.
For more information, see https:\/\/aws.amazon.com/sdk-for-node-js/`;

// The body of the email for recipients whose email clients support HTML content.
var body_html = `<html>
<head></head>
<body>
  <h1>Amazon Pinpoint Test (SDK for JavaScript in Node.js)</h1>
  <p>This email was sent with
    <a href='https://aws.amazon.com/pinpoint/'>the Amazon Pinpoint API</a> using the
    <a href='https://aws.amazon.com/sdk-for-node-js/'>
      AWS SDK for JavaScript in Node.js</a>.</p>
</body>
</html>`;

// The character encoding the you want to use for the subject line and
// message body of the email.
var charset = "UTF-8";

// Specify that you're using a shared credentials file.
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: appId,
  MessageRequest: {
    Addresses: {
      [toAddress]: {
        ChannelType: "EMAIL",
      },
    },
    MessageConfiguration: {
      EmailMessage: {
        FromAddress: senderAddress,
        SimpleEmail: {
          Subject: {
            Charset: charset,
            Data: subject,
          },
          HtmlPart: {
            Charset: charset,
            Data: body_html,
          },
          TextPart: {
            Charset: charset,
            Data: body_text,
          },
        },
      },
    },
  },
};

//Try to send the email.
pinpoint.sendMessages(params, function (err, data) {
  // If something goes wrong, print an error message.
  if (err) {
    console.log(err.message);
  } else {
    console.log(
      "Email sent! Message ID: ",
      data["MessageResponse"]["Result"][toAddress]["MessageId"]
    );
  }
});
```

------
#### [ Python ]

Verwenden Sie dieses Beispiel, um eine E-Mail mithilfe des [AWS SDK für Python (Boto3)](https://aws.amazon.com/sdk-for-python/) zu versenden. Bei diesem Beispiel wird vorausgesetzt, dass Sie das SDK für Python (Boto3) bereits installiert und konfiguriert haben. Weitere Informationen finden Sie unter [Quickstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) in der *API-Referenz zum AWS -SDK für Python (Boto3)*.

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def send_email_message(
    pinpoint_client,
    app_id,
    sender,
    to_addresses,
    char_set,
    subject,
    html_message,
    text_message,
):
    """
    Sends an email message with HTML and plain text versions.

    :param pinpoint_client: A Boto3 Pinpoint client.
    :param app_id: The Amazon Pinpoint project ID to use when you send this message.
    :param sender: The "From" address. This address must be verified in
                   Amazon Pinpoint in the AWS Region you're using to send email.
    :param to_addresses: The addresses on the "To" line. If your Amazon Pinpoint account
                         is in the sandbox, these addresses must be verified.
    :param char_set: The character encoding to use for the subject line and message
                     body of the email.
    :param subject: The subject line of the email.
    :param html_message: The body of the email for recipients whose email clients can
                         display HTML content.
    :param text_message: The body of the email for recipients whose email clients
                         don't support HTML content.
    :return: A dict of to_addresses and their message IDs.
    """
    try:
        response = pinpoint_client.send_messages(
            ApplicationId=app_id,
            MessageRequest={
                "Addresses": {
                    to_address: {"ChannelType": "EMAIL"} for to_address in to_addresses
                },
                "MessageConfiguration": {
                    "EmailMessage": {
                        "FromAddress": sender,
                        "SimpleEmail": {
                            "Subject": {"Charset": char_set, "Data": subject},
                            "HtmlPart": {"Charset": char_set, "Data": html_message},
                            "TextPart": {"Charset": char_set, "Data": text_message},
                        },
                    }
                },
            },
        )
    except ClientError:
        logger.exception("Couldn't send email.")
        raise
    else:
        return {
            to_address: message["MessageId"]
            for to_address, message in response["MessageResponse"]["Result"].items()
        }


def main():
    app_id = "ce796be37f32f178af652b26eexample"
    sender = "sender@example.com"
    to_address = "recipient@example.com"
    char_set = "UTF-8"
    subject = "Amazon Pinpoint Test (SDK for Python (Boto3))"
    text_message = """Amazon Pinpoint Test (SDK for Python)
    -------------------------------------
    This email was sent with Amazon Pinpoint using the AWS SDK for Python (Boto3).
    For more information, see https://aws.amazon.com/sdk-for-python/
                """
    html_message = """<html>
    <head></head>
    <body>
      <h1>Amazon Pinpoint Test (SDK for Python (Boto3)</h1>
      <p>This email was sent with
        <a href='https://aws.amazon.com/pinpoint/'>Amazon Pinpoint</a> using the
        <a href='https://aws.amazon.com/sdk-for-python/'>
          AWS SDK for Python (Boto3)</a>.</p>
    </body>
    </html>
                """

    print("Sending email.")
    message_ids = send_email_message(
        boto3.client("pinpoint"),
        app_id,
        sender,
        [to_address],
        char_set,
        subject,
        html_message,
        text_message,
    )
    print(f"Message sent! Message IDs: {message_ids}")


if __name__ == "__main__":
    main()
```

Sie können Nachrichtenvorlagen auch zum Senden von E-Mail-Nachrichten verwenden, wie im folgenden Beispiel gezeigt:

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def send_templated_email_message(
    pinpoint_client, project_id, sender, to_addresses, template_name, template_version
):
    """
    Sends an email message with HTML and plain text versions.

    :param pinpoint_client: A Boto3 Pinpoint client.
    :param project_id: The Amazon Pinpoint project ID to use when you send this message.
    :param sender: The "From" address. This address must be verified in
                   Amazon Pinpoint in the AWS Region you're using to send email.
    :param to_addresses: The addresses on the "To" line. If your Amazon Pinpoint
                         account is in the sandbox, these addresses must be verified.
    :param template_name: The name of the email template to use when sending the message.
    :param template_version: The version number of the message template.

    :return: A dict of to_addresses and their message IDs.
    """
    try:
        response = pinpoint_client.send_messages(
            ApplicationId=project_id,
            MessageRequest={
                "Addresses": {
                    to_address: {"ChannelType": "EMAIL"} for to_address in to_addresses
                },
                "MessageConfiguration": {"EmailMessage": {"FromAddress": sender}},
                "TemplateConfiguration": {
                    "EmailTemplate": {
                        "Name": template_name,
                        "Version": template_version,
                    }
                },
            },
        )
    except ClientError:
        logger.exception("Couldn't send email.")
        raise
    else:
        return {
            to_address: message["MessageId"]
            for to_address, message in response["MessageResponse"]["Result"].items()
        }


def main():
    project_id = "296b04b342374fceb661bf494example"
    sender = "sender@example.com"
    to_addresses = ["recipient@example.com"]
    template_name = "My_Email_Template"
    template_version = "1"

    print("Sending email.")
    message_ids = send_templated_email_message(
        boto3.client("pinpoint"),
        project_id,
        sender,
        to_addresses,
        template_name,
        template_version,
    )
    print(f"Message sent! Message IDs: {message_ids}")


if __name__ == "__main__":
    main()
```

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen Benutzer anzugeben. Weitere Informationen finden Sie unter [Anmeldeinformation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html) in der *API-Referenz zum AWS -SDK für Python (Boto3)*.

------

# Hinzufügen von Abmelde-Headern zu E-Mails mit Amazon Pinpoint
<a name="send-messages-email-cli"></a>

**Anmerkung**  
Bevor Sie E-Mail-Header verwenden können, müssen Sie eine E-Mail-Orchestration-Senderolle einrichten, wenn Sie E-Mails im Rahmen einer Kampagne oder einer Journey versenden. Für das direkte Senden von E-Mails benötigen Sie Berechtigungen für `ses:SendEmail` und. `ses:SendRawEmail` Weitere Informationen finden Sie unter [Erstellen einer E-Mail-Orchestration-Senderolle](https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-email-orchestration-sending-role.html) im [Amazon Pinpoint Pinpoint-Benutzerhandbuch](https://docs.aws.amazon.com/pinpoint/latest/userguide/).

Es hat sich bewährt, einen Link zum Abbestellen in Ihre E-Mail aufzunehmen. In einigen Ländern ist dies sogar gesetzlich vorgeschrieben. Um einen Link zum Abbestellen mit einem Klick hinzuzufügen, fügen Sie die folgenden Überschriften hinzu: 

1. Setzen Sie den **Header-Namen** auf `List-Unsubscribe` und legen Sie **Wert** auf Ihren Abmeldelink fest. Der Link muss HTTP-POST-Anforderungen unterstützen, um die Abbestellanforderung des Empfängers verarbeiten zu können.

1. Setzen Sie den **Header-Namen** auf `List-Unsubscribe-Post` und legen Sie **den Wert** auf fest`List-Unsubscribe=One-Click`. 

Sie können einer E-Mail-Nachricht bis zu 15 Kopfzeilen hinzufügen. Eine Liste der unterstützten Header finden Sie unter [Amazon SES SES-Header-Felder](https://docs.aws.amazon.com/ses/latest/dg/header-fields.html) im [Amazon Simple Email Service Developer Guide](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/).

Das folgende Beispiel zeigt, wie Sie eine E-Mail-Nachricht mit Abmelde-Headern mithilfe von versenden. AWS Command Line Interface Weitere Informationen zur Konfiguration von finden [Sie unter Configure the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) im [AWS Command Line Interface Benutzerhandbuch](https://docs.aws.amazon.com/cli/latest/userguide/). AWS CLI

Gehen Sie im folgenden Befehl wie folgt vor:
+ *AppId*Ersetzen Sie es durch Ihre Anwendungs-ID.
+ *richard\$1roe@example.com*Ersetzen Sie es durch die E-Mail-Adresse des Empfängers.
+ Ersetzen Sie es *https://example.com/unsub* durch Ihren Abmeldelink.
+ *example123456*Ersetzen Sie es durch eine eindeutige Kennung für den Empfänger.

```
aws pinpoint send-messages --application-id AppId --message-request '{
 "Addresses": {
   "richard_roe@example.com": {
     "ChannelType": "EMAIL"
   }
 },
 "MessageConfiguration": {
   "EmailMessage": {
     "Substitutions": {
       "url": [
         "https://example.com/unsub"
       ],
        "id1": [
          "/example123456"
        ]
     },
     "SimpleEmail": {
       "TextPart": {
         "Data": "Sample email message with an subscribe header",
         "Charset": "UTF-8"
       },
       "Subject": {
         "Data": "Hello",
         "Charset": "UTF-8"
       },
       "Headers": [
         {
           "Name": "List-Unsubscribe",
           "Value": "{{url}}{{id1}}"
         },
         {
           "Name": "List-Unsubscribe-Post",
           "Value": "List-Unsubscribe=One-Click"
         }
       ]
     }
   }
 }
}'
```

# Senden Sie Transaktions-SMS-Nachrichten mit Amazon Pinpoint
<a name="send-messages-sms"></a>

Sie können die Amazon Pinpoint Pinpoint-API verwenden, um SMS-Nachrichten (Textnachrichten) an bestimmte Telefonnummern oder Endgeräte IDs zu senden. Dieser Abschnitt enthält vollständige Codebeispiele, die Sie verwenden können, um SMS-Nachrichten mithilfe eines AWS SDK über die Amazon Pinpoint Pinpoint-API zu versenden. Ihr Konto muss in Produktion sein und Sie müssen über eine aktive Originationsidentität verfügen, mit der SMS-Nachrichten gesendet werden können.

Weitere Codebeispiele zu Endpunkten, Segmenten und Kanälen finden Sie unter [Codebeispiele](https://docs.aws.amazon.com/pinpoint/latest/developerguide/service_code_examples.html).

------
#### [ C\$1 ]

Verwenden Sie dieses Beispiel, um eine SMS-Nachricht mithilfe des [AWS SDK für .NET](https://aws.amazon.com/sdk-for-net/) zu versenden. Bei diesem Beispiel wird vorausgesetzt, dass Sie das SDK für .NET bereits installiert und konfiguriert haben. Weitere Informationen finden Sie unter [Erste Schritte](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config.html) im *AWS SDK für .NET -Entwicklerhandbuch*.

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen IAM-Benutzer anzugeben. Weitere Informationen finden Sie unter [Konfigurieren von AWS -Anmeldeinformationen)](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/creds-idc.html) im *AWS SDK für .NET -Entwicklerhandbuch*.

```
using Amazon;
using Amazon.Pinpoint;
using Amazon.Pinpoint.Model;
using Microsoft.Extensions.Configuration;

namespace SendSmsMessage;

public class SendSmsMessageMainClass
{
    public static async Task Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        // 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/
        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.
        string originationNumber = configuration["OriginationNumber"]!;

        // The recipient's phone number.  For best results, you should specify the
        // phone number in E.164 format.
        string destinationNumber = configuration["DestinationNumber"]!;

        // 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.
        string appId = configuration["AppId"]!;

        // 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.
        MessageType messageType = MessageType.TRANSACTIONAL;

        // The registered keyword associated with the originating short code.
        string? registeredKeyword = configuration["RegisteredKeyword"];

        // 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
        string? senderId = configuration["SenderId"];

        try
        {
            var response = await SendSmsMessage(region, appId, destinationNumber,
                originationNumber, registeredKeyword, senderId, messageType);
            Console.WriteLine($"Message sent to {response.MessageResponse.Result.Count} recipient(s).");
            foreach (var messageResultValue in
                     response.MessageResponse.Result.Select(r => r.Value))
            {
                Console.WriteLine($"{messageResultValue.MessageId} Status: {messageResultValue.DeliveryStatus}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("The message wasn't sent. Error message: " + ex.Message);
        }
    }

    public static async Task<SendMessagesResponse> SendSmsMessage(
        string region, string appId, string destinationNumber, string originationNumber,
        string? keyword, string? senderId, MessageType messageType)
    {

        // The content of the SMS message.
        string message = "This message was sent through Amazon Pinpoint using" +
                         " the AWS SDK for .NET. Reply STOP to opt out.";


        var client = new AmazonPinpointClient(RegionEndpoint.GetBySystemName(region));

        SendMessagesRequest sendRequest = new SendMessagesRequest
        {
            ApplicationId = appId,
            MessageRequest = new MessageRequest
            {
                Addresses =
                    new Dictionary<string, AddressConfiguration>
                    {
                        {
                            destinationNumber,
                            new AddressConfiguration { ChannelType = ChannelType.SMS }
                        }
                    },
                MessageConfiguration = new DirectMessageConfiguration
                {
                    SMSMessage = new SMSMessage
                    {
                        Body = message,
                        MessageType = MessageType.TRANSACTIONAL,
                        OriginationNumber = originationNumber,
                        SenderId = senderId,
                        Keyword = keyword
                    }
                }
            }
        };
        SendMessagesResponse response = await client.SendMessagesAsync(sendRequest);
        return response;
    }
}
```

------
#### [ Java ]

Verwenden Sie dieses Beispiel, um eine SMS-Nachricht mithilfe des [AWS SDK für Java](https://aws.amazon.com/sdk-for-java/) zu versenden. Bei diesem Beispiel wird vorausgesetzt, dass Sie das SDK für Java bereits installiert und konfiguriert haben. Weitere Informationen finden Sie unter [Erste Schritte](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html) im *AWS SDK für Java -Entwicklerhandbuch*.

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen IAM-Benutzer anzugeben. Weitere Informationen finden Sie unter [Einrichten der Standard-Anmeldeinformationen und ‑Region](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html#setup-credentials) im *AWS SDK für Java -Entwicklerhandbuch*.

```
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);
                }
        }
}
```

Das vollständige SDK-Beispiel finden Sie unter [SendMessage.java on. [GitHub](https://github.com/)](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessage.java/)

------
#### [ JavaScript (Node.js) ]

Verwenden Sie dieses Beispiel, um mithilfe des [AWS SDK für JavaScript in Node.js](https://aws.amazon.com/sdk-for-javascript/) eine SMS-Nachricht zu senden. In diesem Beispiel wird vorausgesetzt, dass Sie das SDK für JavaScript in Node.js bereits installiert und konfiguriert haben. Weitere Informationen finden Sie unter [Erste Schritte](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-nodejs.html) im *AWS SDK für JavaScript im Node.js Developer Guide*.

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen IAM-Benutzer anzugeben. Weitere Informationen finden Sie unter [Einrichten von Anmeldeinformationen](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials.html) im *AWS SDK für JavaScript im Node.js Developer Guide*.

```
"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 ]

Verwenden Sie dieses Beispiel, um eine SMS-Nachricht mithilfe des [AWS SDK für Python (Boto3)](https://aws.amazon.com/sdk-for-python/) zu versenden. Bei diesem Beispiel wird vorausgesetzt, dass Sie das SDK für Python bereits installiert und konfiguriert haben. Weitere Informationen finden Sie unter [Schnellstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) in * AWS SDK for Python (Boto3)* Getting Started.

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

Sie können Nachrichtenvorlagen auch zum Senden von SMS-Nachrichten verwenden, wie im folgenden Beispiel gezeigt:

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

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen IAM-Benutzer anzugeben. Weitere Informationen finden Sie unter [Anmeldeinformation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html) in der *API-Referenz zum AWS -SDK für Python (Boto3)*.

------

# Senden Sie Sprachnachrichten mit Amazon Pinpoint
<a name="send-messages-voice"></a>

Sie können die Amazon-Pinpoint-API verwenden, um Sprachnachrichten an bestimmte Telefonnummern zu senden. Dieser Abschnitt enthält vollständige Codebeispiele, die Sie verwenden können, um Sprachnachrichten mithilfe eines AWS SDK über die Amazon Pinpoint SMS and Voice API zu senden. Ihr Konto muss in Produktion sein und Sie müssen über eine aktive Originationsidentität verfügen, mit der Sprachnachrichten gesendet werden können.

Weitere Codebeispiele zu Endpunkten, Segmenten und Kanälen finden Sie unter [Codebeispiele](https://docs.aws.amazon.com/pinpoint/latest/developerguide/service_code_examples.html).

------
#### [ Java ]

Verwenden Sie dieses Beispiel, um eine Sprachnachricht mithilfe des [AWS SDK für Java](https://aws.amazon.com/sdk-for-java/) zu versenden. Bei diesem Beispiel wird vorausgesetzt, dass Sie das SDK für Java bereits installiert und konfiguriert haben. Weitere Informationen finden Sie unter [Erste Schritte](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html) im AWS SDK für Java -Entwicklerhandbuch.

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen Benutzer anzugeben. Weitere Informationen finden Sie im *AWS SDK für Java Entwicklerhandbuch* unter [AWS Zugangsdaten und Region für die Entwicklung einrichten](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html#setup-credentials).

```
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpointsmsvoice.PinpointSmsVoiceClient;
import software.amazon.awssdk.services.pinpointsmsvoice.model.SSMLMessageType;
import software.amazon.awssdk.services.pinpointsmsvoice.model.VoiceMessageContent;
import software.amazon.awssdk.services.pinpointsmsvoice.model.SendVoiceMessageRequest;
import software.amazon.awssdk.services.pinpointsmsvoice.model.PinpointSmsVoiceException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
```

```
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpointsmsvoice.PinpointSmsVoiceClient;
import software.amazon.awssdk.services.pinpointsmsvoice.model.SSMLMessageType;
import software.amazon.awssdk.services.pinpointsmsvoice.model.VoiceMessageContent;
import software.amazon.awssdk.services.pinpointsmsvoice.model.SendVoiceMessageRequest;
import software.amazon.awssdk.services.pinpointsmsvoice.model.PinpointSmsVoiceException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class SendVoiceMessage {

    // The Amazon Polly voice that you want to use to send the message. For a list
    // of voices, see https://docs.aws.amazon.com/polly/latest/dg/voicelist.html
    static final String voiceName = "Matthew";

    // The language to use when sending the message. For a list of supported
    // languages, see
    // https://docs.aws.amazon.com/polly/latest/dg/SupportedLanguage.html
    static final String languageCode = "en-US";

    // The content of the message. This example uses SSML to customize and control
    // certain aspects of the message, such as by adding pauses and changing
    // phonation. The message can't contain any line breaks.
    static final String ssmlMessage = "<speak>This is a test message sent from "
            + "<emphasis>Amazon Pinpoint</emphasis> "
            + "using the <break strength='weak'/>AWS "
            + "SDK for Java. "
            + "<amazon:effect phonation='soft'>Thank "
            + "you for listening.</amazon:effect></speak>";

    public static void main(String[] args) {

        final String usage = """
                Usage:   <originationNumber> <destinationNumber>\s
                
                Where:
                  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 != 2) {
            System.out.println(usage);
            System.exit(1);
        }
        String originationNumber = args[0];
        String destinationNumber = args[1];
        System.out.println("Sending a voice message");

        // Set the content type to application/json.
        List<String> listVal = new ArrayList<>();
        listVal.add("application/json");
        Map<String, List<String>> values = new HashMap<>();
        values.put("Content-Type", listVal);

        ClientOverrideConfiguration config2 = ClientOverrideConfiguration.builder()
                .headers(values)
                .build();

        PinpointSmsVoiceClient client = PinpointSmsVoiceClient.builder()
                .overrideConfiguration(config2)
                .region(Region.US_EAST_1)
                .build();

        sendVoiceMsg(client, originationNumber, destinationNumber);
        client.close();
    }

    public static void sendVoiceMsg(PinpointSmsVoiceClient client, String originationNumber,
                                    String destinationNumber) {
        try {
            SSMLMessageType ssmlMessageType = SSMLMessageType.builder()
                    .languageCode(languageCode)
                    .text(ssmlMessage)
                    .voiceId(voiceName)
                    .build();

            VoiceMessageContent content = VoiceMessageContent.builder()
                    .ssmlMessage(ssmlMessageType)
                    .build();

            SendVoiceMessageRequest voiceMessageRequest = SendVoiceMessageRequest.builder()
                    .destinationPhoneNumber(destinationNumber)
                    .originationPhoneNumber(originationNumber)
                    .content(content)
                    .build();

            client.sendVoiceMessage(voiceMessageRequest);
            System.out.println("The message was sent successfully.");

        } catch (PinpointSmsVoiceException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```

Das vollständige SDK-Beispiel finden Sie unter [SendVoiceMessage.java](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendVoiceMessage.java) on [GitHub](https://github.com/).

------
#### [ JavaScript (Node.js) ]

Verwenden Sie dieses Beispiel, um mithilfe des AWS SDK für JavaScript in Node.js eine Sprachnachricht zu senden. In diesem Beispiel wird vorausgesetzt, dass Sie das SDK für JavaScript in Node.js bereits installiert und konfiguriert haben.

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen Benutzer anzugeben. Weitere Informationen finden Sie unter [Einrichten von Anmeldeinformationen](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials.html) im *AWS SDK für JavaScript im Node.js Developer Guide*.

```
"use strict";

var AWS = require("aws-sdk");

// The AWS Region that you want to use to send the voice message. For a list of
// AWS Regions where the Amazon Pinpoint SMS and Voice API is available, see
// https://docs.aws.amazon.com/pinpoint-sms-voice/latest/APIReference/
var aws_region = "us-east-1";

// The phone number that the message is sent from. The phone number that you
// specify has to be associated with your Amazon Pinpoint account. For best results, you
// should specify the phone number in E.164 format.
var originationNumber = "+12065550110";

// The recipient's phone number. For best results, you should specify the phone
// number in E.164 format.
var destinationNumber = "+12065550142";

// The language to use when sending the message. For a list of supported
// languages, see https://docs.aws.amazon.com/polly/latest/dg/SupportedLanguage.html
var languageCode = "en-US";

// The Amazon Polly voice that you want to use to send the message. For a list
// of voices, see https://docs.aws.amazon.com/polly/latest/dg/voicelist.html
var voiceId = "Matthew";

// The content of the message. This example uses SSML to customize and control
// certain aspects of the message, such as the volume or the speech rate.
// The message can't contain any line breaks.
var ssmlMessage =
  "<speak>" +
  "This is a test message sent from <emphasis>Amazon Pinpoint</emphasis> " +
  "using the <break strength='weak'/>AWS SDK for JavaScript in Node.js. " +
  "<amazon:effect phonation='soft'>Thank you for listening." +
  "</amazon:effect>" +
  "</speak>";

// The phone number that you want to appear on the recipient's device. The phone
// number that you specify has to be associated with your Amazon Pinpoint account.
var callerId = "+12065550199";

// The configuration set that you want to use to send the message.
var configurationSet = "ConfigSet";

// 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 pinpointsmsvoice = new AWS.PinpointSMSVoice();

var params = {
  CallerId: callerId,
  ConfigurationSetName: configurationSet,
  Content: {
    SSMLMessage: {
      LanguageCode: languageCode,
      Text: ssmlMessage,
      VoiceId: voiceId,
    },
  },
  DestinationPhoneNumber: destinationNumber,
  OriginationPhoneNumber: originationNumber,
};

//Try to send the message.
pinpointsmsvoice.sendVoiceMessage(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! Message ID: " + data["MessageId"]);
  }
});
```

------
#### [ Python ]

Verwenden Sie dieses Beispiel, um eine Sprachnachricht mithilfe des AWS SDK für Python (Boto3) zu versenden. Bei diesem Beispiel wird vorausgesetzt, dass Sie das SDK für Python (Boto3) bereits installiert und konfiguriert haben. 

In diesem Beispiel wird davon ausgegangen, dass Sie eine Datei mit gemeinsam genutzten Anmeldeinformationen verwenden, um den Zugriffsschlüssel und den geheimen Zugriffsschlüssel für einen vorhandenen Benutzer anzugeben. Weitere Informationen finden Sie unter [Anmeldeinformation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html) in der *API-Referenz zum AWS -SDK für Python (Boto3)*.

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def send_voice_message(
    sms_voice_client,
    origination_number,
    caller_id,
    destination_number,
    language_code,
    voice_id,
    ssml_message,
):
    """
    Sends a voice message using speech synthesis provided by Amazon Polly.

    :param sms_voice_client: A Boto3 PinpointSMSVoice client.
    :param origination_number: The phone number that the message is sent from.
                               The phone number must be associated with your Amazon
                               Pinpoint account and be in E.164 format.
    :param caller_id: The phone number that you want to appear on the recipient's
                      device. The phone number must be associated with your Amazon
                      Pinpoint account and be in E.164 format.
    :param destination_number: The recipient's phone number. Specify the phone
                               number in E.164 format.
    :param language_code: The language to use when sending the message.
    :param voice_id: The Amazon Polly voice that you want to use to send the message.
    :param ssml_message: The content of the message. This example uses SSML to control
                         certain aspects of the message, such as the volume and the
                         speech rate. The message must not contain line breaks.
    :return: The ID of the message.
    """
    try:
        response = sms_voice_client.send_voice_message(
            DestinationPhoneNumber=destination_number,
            OriginationPhoneNumber=origination_number,
            CallerId=caller_id,
            Content={
                "SSMLMessage": {
                    "LanguageCode": language_code,
                    "VoiceId": voice_id,
                    "Text": ssml_message,
                }
            },
        )
    except ClientError:
        logger.exception(
            "Couldn't send message from %s to %s.",
            origination_number,
            destination_number,
        )
        raise
    else:
        return response["MessageId"]


def main():
    origination_number = "+12065550110"
    caller_id = "+12065550199"
    destination_number = "+12065550142"
    language_code = "en-US"
    voice_id = "Matthew"
    ssml_message = (
        "<speak>"
        "This is a test message sent from <emphasis>Amazon Pinpoint</emphasis> "
        "using the <break strength='weak'/>AWS SDK for Python (Boto3). "
        "<amazon:effect phonation='soft'>Thank you for listening."
        "</amazon:effect>"
        "</speak>"
    )
    print(f"Sending voice message from {origination_number} to {destination_number}.")
    message_id = send_voice_message(
        boto3.client("pinpoint-sms-voice"),
        origination_number,
        caller_id,
        destination_number,
        language_code,
        voice_id,
        ssml_message,
    )
    print(f"Message sent!\nMessage ID: {message_id}")


if __name__ == "__main__":
    main()
```

------