SendEmailÚselo con un AWS SDK - AWS SDKEjemplos de código

Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

SendEmailÚselo con un AWS SDK

En los siguientes ejemplos de código se muestra cómo se utiliza SendEmail.

.NET
AWS SDK for .NET
nota

Hay más en marcha GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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; }
  • Para API obtener más información, consulte SendEmailla AWS SDK for .NET APIReferencia.

Java
SDKpara Java 2.x
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envía un mensaje.

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

Envía un mensaje mediante una plantilla.

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()); }
  • Para API obtener más información, consulte SendEmailla AWS SDK for Java 2.x APIReferencia.

Python
SDKpara Python (Boto3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envía un mensaje a todos los miembros de la lista de contactos.

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}'.")

Envía un mensaje a todos los miembros de la lista de contactos mediante una plantilla.

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}, )
  • Para API obtener más información, consulte SendEmailla AWS SDKreferencia de Python (Boto3). API

Ruby
SDKpara Ruby
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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)
  • Para API obtener más información, consulte SendEmailla AWS SDK for Ruby APIReferencia.

Rust
SDKpara Rust
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envía un mensaje a todos los miembros de la lista de contactos.

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

Envía un mensaje a todos los miembros de la lista de contactos mediante una plantilla.

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)), }
  • Para API obtener más información, consulte SendEmailla AWS SDKAPIreferencia sobre Rust.