À utiliser SendEmail avec un AWS SDK ou CLI - Exemples de code de l'AWS SDK

D'autres AWS SDK exemples sont disponibles dans le GitHub dépôt AWS Doc SDK Examples.

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

À utiliser SendEmail avec un AWS SDK ou CLI

Les exemples de code suivants montrent comment utiliserSendEmail.

.NET
AWS SDK for .NET
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/// <summary> /// Sends an email with the specified content and options. /// </summary> /// <param name="fromEmailAddress">The email address to send the email from.</param> /// <param name="toEmailAddresses">The email addresses to send the email to.</param> /// <param name="subject">The subject of the email.</param> /// <param name="htmlContent">The HTML content of the email.</param> /// <param name="textContent">The text content of the email.</param> /// <param name="templateName">The name of the email template to use (optional).</param> /// <param name="templateData">The data to replace placeholders in the email template (optional).</param> /// <param name="contactListName">The name of the contact list for unsubscribe functionality (optional).</param> /// <returns>The MessageId response from the SendEmail operation.</returns> public async Task<string> SendEmailAsync(string fromEmailAddress, List<string> toEmailAddresses, string? subject, string? htmlContent, string? textContent, string? templateName = null, string? templateData = null, string? contactListName = null) { var request = new SendEmailRequest { FromEmailAddress = fromEmailAddress }; if (toEmailAddresses.Any()) { request.Destination = new Destination { ToAddresses = toEmailAddresses }; } if (!string.IsNullOrEmpty(templateName)) { request.Content = new EmailContent() { Template = new Template { TemplateName = templateName, TemplateData = templateData } }; } else { request.Content = new EmailContent { Simple = new Message { Subject = new Content { Data = subject }, Body = new Body { Html = new Content { Data = htmlContent }, Text = new Content { Data = textContent } } } }; } if (!string.IsNullOrEmpty(contactListName)) { request.ListManagementOptions = new ListManagementOptions { ContactListName = contactListName }; } try { var response = await _sesClient.SendEmailAsync(request); return response.MessageId; } catch (AccountSuspendedException ex) { Console.WriteLine("The account's ability to send email has been permanently restricted."); Console.WriteLine(ex.Message); } catch (MailFromDomainNotVerifiedException ex) { Console.WriteLine("The sending domain is not verified."); Console.WriteLine(ex.Message); } catch (MessageRejectedException ex) { Console.WriteLine("The message content is invalid."); Console.WriteLine(ex.Message); } catch (SendingPausedException ex) { Console.WriteLine("The account's ability to send email is currently paused."); Console.WriteLine(ex.Message); } catch (TooManyRequestsException ex) { Console.WriteLine("Too many requests were made. Please try again later."); Console.WriteLine(ex.Message); } catch (Exception ex) { Console.WriteLine($"An error occurred while sending the email: {ex.Message}"); } return string.Empty; }
  • Pour API plus de détails, voir SendEmailla section AWS SDK for .NET APIRéférence.

Java
SDKpour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Envoie un message.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sesv2.model.Body; import software.amazon.awssdk.services.sesv2.model.Content; import software.amazon.awssdk.services.sesv2.model.Destination; import software.amazon.awssdk.services.sesv2.model.EmailContent; import software.amazon.awssdk.services.sesv2.model.Message; import software.amazon.awssdk.services.sesv2.model.SendEmailRequest; import software.amazon.awssdk.services.sesv2.model.SesV2Exception; import software.amazon.awssdk.services.sesv2.SesV2Client; /** * Before running this AWS SDK for Java (v2) 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 SendEmail { 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; SesV2Client sesv2Client = SesV2Client.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>"; send(sesv2Client, sender, recipient, subject, bodyHTML); } public static void send(SesV2Client client, String sender, String recipient, String subject, String bodyHTML) { 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(); EmailContent emailContent = EmailContent.builder() .simple(msg) .build(); SendEmailRequest emailRequest = SendEmailRequest.builder() .destination(destination) .content(emailContent) .fromEmailAddress(sender) .build(); try { System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java..."); client.sendEmail(emailRequest); System.out.println("email was sent"); } catch (SesV2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

Envoie un message à l'aide d'un modèle.

String coupons = Files.readString(Paths.get("resources/coupon_newsletter/sample_coupons.json")); for (String emailAddress : contactEmails) { SendEmailRequest newsletterRequest = SendEmailRequest.builder() .destination(Destination.builder().toAddresses(emailAddress).build()) .content(EmailContent.builder() .template(Template.builder() .templateName(TEMPLATE_NAME) .templateData(coupons) .build()) .build()) .fromEmailAddress(this.verifiedEmail) .listManagementOptions(ListManagementOptions.builder() .contactListName(CONTACT_LIST_NAME) .build()) .build(); SendEmailResponse newsletterResponse = sesClient.sendEmail(newsletterRequest); System.out.println("Newsletter sent to " + emailAddress + ": " + newsletterResponse.messageId()); }
  • Pour API plus de détails, voir SendEmailla section AWS SDK for Java 2.x APIRéférence.

Python
SDKpour Python (Boto3)
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Envoie un message à tous les membres de la liste de contacts.

def main(): """ The main function that orchestrates the execution of the workflow. """ print(INTRO) ses_client = boto3.client("sesv2") workflow = SESv2Workflow(ses_client) try: workflow.prepare_application() workflow.gather_subscriber_email_addresses() workflow.send_coupon_newsletter() workflow.monitor_and_review() except ClientError as e: print_error(e) workflow.clean_up() class SESv2Workflow: """ A class to manage the SES v2 Coupon Newsletter Workflow. """ def __init__(self, ses_client, sleep=True): self.ses_client = ses_client self.sleep = sleep self.ses_client.send_email( FromEmailAddress=self.verified_email, Destination={"ToAddresses": [email]}, Content={ "Simple": { "Subject": { "Data": "Welcome to the Weekly Coupons Newsletter" }, "Body": { "Text": {"Data": welcome_text}, "Html": {"Data": welcome_html}, }, } }, ) print(f"Welcome email sent to '{email}'.")

Envoie un message à tous les membres de la liste de contacts à l'aide d'un modèle.

def main(): """ The main function that orchestrates the execution of the workflow. """ print(INTRO) ses_client = boto3.client("sesv2") workflow = SESv2Workflow(ses_client) try: workflow.prepare_application() workflow.gather_subscriber_email_addresses() workflow.send_coupon_newsletter() workflow.monitor_and_review() except ClientError as e: print_error(e) workflow.clean_up() class SESv2Workflow: """ A class to manage the SES v2 Coupon Newsletter Workflow. """ def __init__(self, ses_client, sleep=True): self.ses_client = ses_client self.sleep = sleep self.ses_client.send_email( FromEmailAddress=self.verified_email, Destination={"ToAddresses": [email_address]}, Content={ "Template": { "TemplateName": TEMPLATE_NAME, "TemplateData": coupon_items, } }, ListManagementOptions={"ContactListName": CONTACT_LIST_NAME}, )
  • Pour API plus de détails, reportez-vous SendEmailà la section AWS SDKrelative à la référence Python (Boto3). API

Ruby
SDKpour Ruby
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

require "aws-sdk-sesv2" require_relative "config" # Recipient and sender email addresses. # Set up the SESv2 client. client = Aws::SESV2::Client.new(region: AWS_REGION) def send_email(client, sender_email, recipient_email) response = client.send_email( { from_email_address: sender_email, destination: { to_addresses: [recipient_email] }, content: { simple: { subject: { data: "Test email subject" }, body: { text: { data: "Test email body" } } } } } ) puts "Email sent from #{SENDER_EMAIL} to #{RECIPIENT_EMAIL} with message ID: #{response.message_id}" end send_email(client, SENDER_EMAIL, RECIPIENT_EMAIL)
  • Pour API plus de détails, voir SendEmailla section AWS SDK for Ruby APIRéférence.

Rust
SDKpour Rust
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Envoie un message à tous les membres de la liste de contacts.

async fn send_message( client: &Client, list: &str, from: &str, subject: &str, message: &str, ) -> Result<(), Error> { // Get list of email addresses from contact list. let resp = client .list_contacts() .contact_list_name(list) .send() .await?; let contacts = resp.contacts(); let cs: Vec<String> = contacts .iter() .map(|i| i.email_address().unwrap_or_default().to_string()) .collect(); let mut dest: Destination = Destination::builder().build(); dest.to_addresses = Some(cs); let subject_content = Content::builder() .data(subject) .charset("UTF-8") .build() .expect("building Content"); let body_content = Content::builder() .data(message) .charset("UTF-8") .build() .expect("building Content"); let body = Body::builder().text(body_content).build(); let msg = Message::builder() .subject(subject_content) .body(body) .build(); let email_content = EmailContent::builder().simple(msg).build(); client .send_email() .from_email_address(from) .destination(dest) .content(email_content) .send() .await?; println!("Email sent to list"); Ok(()) }

Envoie un message à tous les membres de la liste de contacts à l'aide d'un modèle.

let coupons = std::fs::read_to_string("../resources/newsletter/sample_coupons.json") .unwrap_or_else(|_| r#"{"coupons":[]}"#.to_string()); let email_content = EmailContent::builder() .template( Template::builder() .template_name(TEMPLATE_NAME) .template_data(coupons) .build(), ) .build(); match self .client .send_email() .from_email_address(self.verified_email.clone()) .destination(Destination::builder().to_addresses(email.clone()).build()) .content(email_content) .list_management_options( ListManagementOptions::builder() .contact_list_name(CONTACT_LIST_NAME) .build()?, ) .send() .await { Ok(output) => { if let Some(message_id) = output.message_id { writeln!( self.stdout, "Newsletter sent to {} with message ID {}", email, message_id )?; } else { writeln!(self.stdout, "Newsletter sent to {}", email)?; } } Err(e) => return Err(anyhow!("Error sending newsletter to {}: {}", email, e)), }
  • Pour API plus de détails, reportez-vous SendEmailà la section AWS SDKpour la API référence à Rust.