Verwenden Sie SendEmail mit einem AWS SDK oder CLI - AWS SDK-Codebeispiele

Weitere AWS SDK Beispiele sind im Repo AWS Doc SDK Examples GitHub verfügbar.

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.

Verwenden Sie SendEmail mit einem AWS SDK oder CLI

Die folgenden Codebeispiele zeigen die VerwendungSendEmail.

Beispiele für Aktionen sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Im folgenden Codebeispiel können Sie diese Aktion im Kontext sehen:

.NET
AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

/// <summary> /// Send an email by using Amazon SES. /// </summary> /// <param name="toAddresses">List of recipients.</param> /// <param name="ccAddresses">List of cc recipients.</param> /// <param name="bccAddresses">List of bcc recipients.</param> /// <param name="bodyHtml">Body of the email in HTML.</param> /// <param name="bodyText">Body of the email in plain text.</param> /// <param name="subject">Subject line of the email.</param> /// <param name="senderAddress">From address.</param> /// <returns>The messageId of the email.</returns> public async Task<string> SendEmailAsync(List<string> toAddresses, List<string> ccAddresses, List<string> bccAddresses, string bodyHtml, string bodyText, string subject, string senderAddress) { var messageId = ""; try { var response = await _amazonSimpleEmailService.SendEmailAsync( new SendEmailRequest { Destination = new Destination { BccAddresses = bccAddresses, CcAddresses = ccAddresses, ToAddresses = toAddresses }, Message = new Message { Body = new Body { Html = new Content { Charset = "UTF-8", Data = bodyHtml }, Text = new Content { Charset = "UTF-8", Data = bodyText } }, Subject = new Content { Charset = "UTF-8", Data = subject } }, Source = senderAddress }); messageId = response.MessageId; } catch (Exception ex) { Console.WriteLine("SendEmailAsync failed with exception: " + ex.Message); } return messageId; }
  • APIEinzelheiten finden Sie SendEmailunter AWS SDK for .NET APIReferenz.

C++
SDKfür C++
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

//! Send an email to a list of recipients. /*! \param recipients; Vector of recipient email addresses. \param subject: Email subject. \param htmlBody: Email body as HTML. At least one body data is required. \param textBody: Email body as plain text. At least one body data is required. \param senderEmailAddress: Email address of sender. Ignored if empty string. \param ccAddresses: Vector of cc addresses. Ignored if empty. \param replyToAddress: Reply to email address. Ignored if empty string. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SES::sendEmail(const Aws::Vector<Aws::String> &recipients, const Aws::String &subject, const Aws::String &htmlBody, const Aws::String &textBody, const Aws::String &senderEmailAddress, const Aws::Vector<Aws::String> &ccAddresses, const Aws::String &replyToAddress, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SES::SESClient sesClient(clientConfiguration); Aws::SES::Model::Destination destination; if (!ccAddresses.empty()) { destination.WithCcAddresses(ccAddresses); } if (!recipients.empty()) { destination.WithToAddresses(recipients); } Aws::SES::Model::Body message_body; if (!htmlBody.empty()) { message_body.SetHtml( Aws::SES::Model::Content().WithCharset("UTF-8").WithData(htmlBody)); } if (!textBody.empty()) { message_body.SetText( Aws::SES::Model::Content().WithCharset("UTF-8").WithData(textBody)); } Aws::SES::Model::Message message; message.SetBody(message_body); message.SetSubject( Aws::SES::Model::Content().WithCharset("UTF-8").WithData(subject)); Aws::SES::Model::SendEmailRequest sendEmailRequest; sendEmailRequest.SetDestination(destination); sendEmailRequest.SetMessage(message); if (!senderEmailAddress.empty()) { sendEmailRequest.SetSource(senderEmailAddress); } if (!replyToAddress.empty()) { sendEmailRequest.AddReplyToAddresses(replyToAddress); } auto outcome = sesClient.SendEmail(sendEmailRequest); if (outcome.IsSuccess()) { std::cout << "Successfully sent message with ID " << outcome.GetResult().GetMessageId() << "." << std::endl; } else { std::cerr << "Error sending message. " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • APIEinzelheiten finden Sie SendEmailunter AWS SDK for C++ APIReferenz.

CLI
AWS CLI

Um eine formatierte E-Mail mit Amazon zu senden SES

Im folgenden Beispiel wird der send-email-Befehl verwendet, um eine formatierte E-Mail zu senden:

aws ses send-email --from sender@example.com --destination file://destination.json --message file://message.json

Ausgabe:

{ "MessageId": "EXAMPLEf3a5efcd1-51adec81-d2a4-4e3f-9fe2-5d85c1b23783-000000" }

Das Ziel und die Nachricht sind JSON Datenstrukturen, die in JSON-Dateien im aktuellen Verzeichnis gespeichert sind. Es handelt sich dabei um die folgenden Dateien:

destination.json:

{ "ToAddresses": ["recipient1@example.com", "recipient2@example.com"], "CcAddresses": ["recipient3@example.com"], "BccAddresses": [] }

message.json:

{ "Subject": { "Data": "Test email sent using the AWS CLI", "Charset": "UTF-8" }, "Body": { "Text": { "Data": "This is the message body in text format.", "Charset": "UTF-8" }, "Html": { "Data": "This message body contains HTML formatting. It can, for example, contain links like this one: <a class=\"ulink\" href=\"http://docs.aws.amazon.com/ses/latest/DeveloperGuide\" target=\"_blank\">Amazon SES Developer Guide</a>.", "Charset": "UTF-8" } } }

Ersetzen Sie die Absender- und Empfänger-E-Mail-Adressen durch die Adressen, die Sie verwenden möchten. Beachten Sie, dass die E-Mail-Adresse des Absenders bei Amazon verifiziert werden mussSES. Bis Ihnen Produktionszugriff auf Amazon gewährt wirdSES, müssen Sie auch die E-Mail-Adresse jedes Empfängers verifizieren, es sei denn, es handelt sich bei dem Empfänger um den SES Amazon-Postfachsimulator. Weitere Informationen zur Überprüfung finden Sie unter Verifizieren von E-Mail-Adressen und Domains bei Amazon SES im Amazon Simple Email Service Developer Guide.

Die Nachrichten-ID in der Ausgabe gibt an, dass der Aufruf von send-email erfolgreich war.

Wenn Sie die E-Mail nicht erhalten, überprüfen Sie Ihr Junk-Postfach.

Weitere Informationen zum Senden formatierter E-Mails finden Sie unter Senden formatierter E-Mails über Amazon SES API im Amazon Simple Email Service Developer Guide.

  • APIEinzelheiten finden Sie SendEmailin der AWS CLI Befehlsreferenz.

Java
SDKfür Java 2.x
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ses.SesClient; import software.amazon.awssdk.services.ses.model.Content; import software.amazon.awssdk.services.ses.model.Destination; import software.amazon.awssdk.services.ses.model.Message; import software.amazon.awssdk.services.ses.model.Body; import software.amazon.awssdk.services.ses.model.SendEmailRequest; import software.amazon.awssdk.services.ses.model.SesException; import javax.mail.MessagingException; /** * 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 SendMessageEmailRequest { public static void main(String[] args) { final String usage = """ Usage: <sender> <recipient> <subject>\s Where: sender - An email address that represents the sender.\s recipient - An email address that represents the recipient.\s subject - The subject line.\s """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String sender = args[0]; String recipient = args[1]; String subject = args[2]; Region region = Region.US_EAST_1; SesClient client = SesClient.builder() .region(region) .build(); // The HTML body of the email. String bodyHTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>" + "<p> See the list of customers.</p>" + "</body>" + "</html>"; try { send(client, sender, recipient, subject, bodyHTML); client.close(); System.out.println("Done"); } catch (MessagingException e) { e.getStackTrace(); } } public static void send(SesClient client, String sender, String recipient, String subject, String bodyHTML) throws MessagingException { Destination destination = Destination.builder() .toAddresses(recipient) .build(); Content content = Content.builder() .data(bodyHTML) .build(); Content sub = Content.builder() .data(subject) .build(); Body body = Body.builder() .html(content) .build(); Message msg = Message.builder() .subject(sub) .body(body) .build(); SendEmailRequest emailRequest = SendEmailRequest.builder() .destination(destination) .message(msg) .source(sender) .build(); try { System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java..."); client.sendEmail(emailRequest); } catch (SesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ses.SesClient; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeBodyPart; import javax.mail.util.ByteArrayDataSource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.Properties; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.ses.model.SendRawEmailRequest; import software.amazon.awssdk.services.ses.model.RawMessage; import software.amazon.awssdk.services.ses.model.SesException; /** * 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 SendMessageAttachment { public static void main(String[] args) throws IOException { final String usage = """ Usage: <sender> <recipient> <subject> <fileLocation>\s Where: sender - An email address that represents the sender.\s recipient - An email address that represents the recipient.\s subject - The subject line.\s fileLocation - The location of a Microsoft Excel file to use as an attachment (C:/AWS/customers.xls).\s """; if (args.length != 4) { System.out.println(usage); System.exit(1); } String sender = args[0]; String recipient = args[1]; String subject = args[2]; String fileLocation = args[3]; // The email body for recipients with non-HTML email clients. String bodyText = "Hello,\r\n" + "Please see the attached file for a list " + "of customers to contact."; // The HTML body of the email. String bodyHTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>" + "<p>Please see the attached file for a " + "list of customers to contact.</p>" + "</body>" + "</html>"; Region region = Region.US_WEST_2; SesClient client = SesClient.builder() .region(region) .build(); try { sendemailAttachment(client, sender, recipient, subject, bodyText, bodyHTML, fileLocation); client.close(); System.out.println("Done"); } catch (IOException | MessagingException e) { e.getStackTrace(); } } public static void sendemailAttachment(SesClient client, String sender, String recipient, String subject, String bodyText, String bodyHTML, String fileLocation) throws AddressException, MessagingException, IOException { java.io.File theFile = new java.io.File(fileLocation); byte[] fileContent = Files.readAllBytes(theFile.toPath()); Session session = Session.getDefaultInstance(new Properties()); // Create a new MimeMessage object. MimeMessage message = new MimeMessage(session); // Add subject, from and to lines. message.setSubject(subject, "UTF-8"); message.setFrom(new InternetAddress(sender)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); // Create a multipart/alternative child container. MimeMultipart msgBody = new MimeMultipart("alternative"); // Create a wrapper for the HTML and text parts. MimeBodyPart wrap = new MimeBodyPart(); // Define the text part. MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(bodyText, "text/plain; charset=UTF-8"); // Define the HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(bodyHTML, "text/html; charset=UTF-8"); // Add the text and HTML parts to the child container. msgBody.addBodyPart(textPart); msgBody.addBodyPart(htmlPart); // Add the child container to the wrapper object. wrap.setContent(msgBody); // Create a multipart/mixed parent container. MimeMultipart msg = new MimeMultipart("mixed"); // Add the parent container to the message. message.setContent(msg); msg.addBodyPart(wrap); // Define the attachment. MimeBodyPart att = new MimeBodyPart(); DataSource fds = new ByteArrayDataSource(fileContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); att.setDataHandler(new DataHandler(fds)); String reportName = "WorkReport.xls"; att.setFileName(reportName); // Add the attachment to the message. msg.addBodyPart(att); try { System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java..."); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); message.writeTo(outputStream); ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray()); byte[] arr = new byte[buf.remaining()]; buf.get(arr); SdkBytes data = SdkBytes.fromByteArray(arr); RawMessage rawMessage = RawMessage.builder() .data(data) .build(); SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder() .rawMessage(rawMessage) .build(); client.sendRawEmail(rawEmailRequest); } catch (SesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("Email sent using SesClient with attachment"); } }
  • APIEinzelheiten finden Sie SendEmailunter AWS SDK for Java 2.x APIReferenz.

JavaScript
SDKfür JavaScript (v3)
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

import { SendEmailCommand } from "@aws-sdk/client-ses"; import { sesClient } from "./libs/sesClient.js"; const createSendEmailCommand = (toAddress, fromAddress) => { return new SendEmailCommand({ Destination: { /* required */ CcAddresses: [ /* more items */ ], ToAddresses: [ toAddress, /* more To-email addresses */ ], }, Message: { /* required */ Body: { /* required */ Html: { Charset: "UTF-8", Data: "HTML_FORMAT_BODY", }, Text: { Charset: "UTF-8", Data: "TEXT_FORMAT_BODY", }, }, Subject: { Charset: "UTF-8", Data: "EMAIL_SUBJECT", }, }, Source: fromAddress, ReplyToAddresses: [ /* more items */ ], }); }; const run = async () => { const sendEmailCommand = createSendEmailCommand( "recipient@example.com", "sender@example.com", ); try { return await sesClient.send(sendEmailCommand); } catch (caught) { if (caught instanceof Error && caught.name === "MessageRejected") { /** @type { import('@aws-sdk/client-ses').MessageRejected} */ const messageRejectedError = caught; return messageRejectedError; } throw caught; } };
  • APIEinzelheiten finden Sie SendEmailunter AWS SDK for JavaScript APIReferenz.

Python
SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

class SesMailSender: """Encapsulates functions to send emails with Amazon SES.""" def __init__(self, ses_client): """ :param ses_client: A Boto3 Amazon SES client. """ self.ses_client = ses_client def send_email(self, source, destination, subject, text, html, reply_tos=None): """ Sends an email. Note: If your account is in the Amazon SES sandbox, the source and destination email accounts must both be verified. :param source: The source email account. :param destination: The destination email account. :param subject: The subject of the email. :param text: The plain text version of the body of the email. :param html: The HTML version of the body of the email. :param reply_tos: Email accounts that will receive a reply if the recipient replies to the message. :return: The ID of the message, assigned by Amazon SES. """ send_args = { "Source": source, "Destination": destination.to_service_format(), "Message": { "Subject": {"Data": subject}, "Body": {"Text": {"Data": text}, "Html": {"Data": html}}, }, } if reply_tos is not None: send_args["ReplyToAddresses"] = reply_tos try: response = self.ses_client.send_email(**send_args) message_id = response["MessageId"] logger.info( "Sent mail %s from %s to %s.", message_id, source, destination.tos ) except ClientError: logger.exception( "Couldn't send mail from %s to %s.", source, destination.tos ) raise else: return message_id
  • APIEinzelheiten finden Sie unter SendEmailPython (Boto3) API -Referenz.AWS SDK

Ruby
SDKfür Ruby
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

require "aws-sdk-ses" # v2: require 'aws-sdk' # Replace sender@example.com with your "From" address. # This address must be verified with Amazon SES. sender = "sender@example.com" # Replace recipient@example.com with a "To" address. If your account # is still in the sandbox, this address must be verified. recipient = "recipient@example.com" # Specify a configuration set. To use a configuration # set, uncomment the next line and line 74. # configsetname = "ConfigSet" # The subject line for the email. subject = "Amazon SES test (AWS SDK for Ruby)" # The HTML body of the email. htmlbody = "<h1>Amazon SES test (AWS SDK for Ruby)</h1>"\ '<p>This email was sent with <a href="https://aws.amazon.com/ses/">'\ 'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-ruby/">'\ "AWS SDK for Ruby</a>." # The email body for recipients with non-HTML email clients. textbody = "This email was sent with Amazon SES using the AWS SDK for Ruby." # Specify the text encoding scheme. encoding = "UTF-8" # Create a new SES client in the us-west-2 region. # Replace us-west-2 with the AWS Region you're using for Amazon SES. ses = Aws::SES::Client.new(region: "us-west-2") # Try to send the email. begin # Provide the contents of the email. ses.send_email( destination: { to_addresses: [ recipient ] }, message: { body: { html: { charset: encoding, data: htmlbody }, text: { charset: encoding, data: textbody } }, subject: { charset: encoding, data: subject } }, source: sender, # Uncomment the following line to use a configuration set. # configuration_set_name: configsetname, ) puts "Email sent to " + recipient # If something goes wrong, display an error message. rescue Aws::SES::Errors::ServiceError => error puts "Email not sent. Error message: #{error}" end
  • APIEinzelheiten finden Sie SendEmailunter AWS SDK for Ruby APIReferenz.