Exemplos da Amazon SES API v2 usando SDK para Java 2.x - AWS SDK for Java 2.x

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Exemplos da Amazon SES API v2 usando SDK para Java 2.x

Os exemplos de código a seguir mostram como realizar ações e implementar cenários comuns usando o AWS SDK for Java 2.x com a Amazon SES API v2.

Ações são trechos de código de programas maiores e devem ser executadas em contexto. Embora as ações mostrem como chamar funções de serviço específicas, é possível ver as ações contextualizadas em seus devidos cenários e exemplos entre serviços.

Cenários são exemplos de código que mostram como realizar uma tarefa específica chamando várias funções dentro do mesmo serviço.

Cada exemplo inclui um link para GitHub, onde você pode encontrar instruções sobre como configurar e executar o código no contexto.

Ações

O código de exemplo a seguir mostra como usar CreateContact.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

try { // Create a new contact with the provided email address in the CreateContactRequest contactRequest = CreateContactRequest.builder() .contactListName(CONTACT_LIST_NAME) .emailAddress(emailAddress) .build(); sesClient.createContact(contactRequest); contacts.add(emailAddress); System.out.println("Contact created: " + emailAddress); // Send a welcome email to the new contact String welcomeHtml = Files.readString(Paths.get("resources/coupon_newsletter/welcome.html")); String welcomeText = Files.readString(Paths.get("resources/coupon_newsletter/welcome.txt")); SendEmailRequest welcomeEmailRequest = SendEmailRequest.builder() .fromEmailAddress(this.verifiedEmail) .destination(Destination.builder().toAddresses(emailAddress).build()) .content(EmailContent.builder() .simple( Message.builder() .subject(Content.builder().data("Welcome to the Weekly Coupons Newsletter").build()) .body(Body.builder() .text(Content.builder().data(welcomeText).build()) .html(Content.builder().data(welcomeHtml).build()) .build()) .build()) .build()) .build(); SendEmailResponse welcomeEmailResponse = sesClient.sendEmail(welcomeEmailRequest); System.out.println("Welcome email sent: " + welcomeEmailResponse.messageId()); } catch (AlreadyExistsException e) { // If the contact already exists, skip this step for that contact and proceed // with the next contact System.out.println("Contact already exists, skipping creation..."); } catch (Exception e) { System.err.println("Error occurred while processing email address " + emailAddress + ": " + e.getMessage()); throw e; } }
  • Para API obter detalhes, consulte CreateContactem AWS SDK for Java 2.x APIReferência.

O código de exemplo a seguir mostra como usar CreateContactList.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

try { // 2. Create a contact list String contactListName = CONTACT_LIST_NAME; CreateContactListRequest createContactListRequest = CreateContactListRequest.builder() .contactListName(contactListName) .build(); sesClient.createContactList(createContactListRequest); System.out.println("Contact list created: " + contactListName); } catch (AlreadyExistsException e) { System.out.println("Contact list already exists, skipping creation: weekly-coupons-newsletter"); } catch (LimitExceededException e) { System.err.println("Limit for contact lists has been exceeded."); throw e; } catch (SesV2Exception e) { System.err.println("Error creating contact list: " + e.getMessage()); throw e; }
  • Para API obter detalhes, consulte CreateContactListem AWS SDK for Java 2.x APIReferência.

O código de exemplo a seguir mostra como usar CreateEmailIdentity.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

try { CreateEmailIdentityRequest createEmailIdentityRequest = CreateEmailIdentityRequest.builder() .emailIdentity(verifiedEmail) .build(); sesClient.createEmailIdentity(createEmailIdentityRequest); System.out.println("Email identity created: " + verifiedEmail); } catch (AlreadyExistsException e) { System.out.println("Email identity already exists, skipping creation: " + verifiedEmail); } catch (NotFoundException e) { System.err.println("The provided email address is not verified: " + verifiedEmail); throw e; } catch (LimitExceededException e) { System.err .println("You have reached the limit for email identities. Please remove some identities and try again."); throw e; } catch (SesV2Exception e) { System.err.println("Error creating email identity: " + e.getMessage()); throw e; }

O código de exemplo a seguir mostra como usar CreateEmailTemplate.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

try { // Create an email template named "weekly-coupons" String newsletterHtml = loadFile("resources/coupon_newsletter/coupon-newsletter.html"); String newsletterText = loadFile("resources/coupon_newsletter/coupon-newsletter.txt"); CreateEmailTemplateRequest templateRequest = CreateEmailTemplateRequest.builder() .templateName(TEMPLATE_NAME) .templateContent(EmailTemplateContent.builder() .subject("Weekly Coupons Newsletter") .html(newsletterHtml) .text(newsletterText) .build()) .build(); sesClient.createEmailTemplate(templateRequest); System.out.println("Email template created: " + TEMPLATE_NAME); } catch (AlreadyExistsException e) { // If the template already exists, skip this step and proceed with the next // operation System.out.println("Email template already exists, skipping creation..."); } catch (LimitExceededException e) { // If the limit for email templates is exceeded, fail the workflow and inform // the user System.err.println("You have reached the limit for email templates. Please remove some templates and try again."); throw e; } catch (Exception e) { System.err.println("Error occurred while creating email template: " + e.getMessage()); throw e; }

O código de exemplo a seguir mostra como usar DeleteContactList.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

try { // Delete the contact list DeleteContactListRequest deleteContactListRequest = DeleteContactListRequest.builder() .contactListName(CONTACT_LIST_NAME) .build(); sesClient.deleteContactList(deleteContactListRequest); System.out.println("Contact list deleted: " + CONTACT_LIST_NAME); } catch (NotFoundException e) { // If the contact list does not exist, log the error and proceed System.out.println("Contact list not found. Skipping deletion..."); } catch (Exception e) { System.err.println("Error occurred while deleting the contact list: " + e.getMessage()); e.printStackTrace(); }
  • Para API obter detalhes, consulte DeleteContactListem AWS SDK for Java 2.x APIReferência.

O código de exemplo a seguir mostra como usar DeleteEmailIdentity.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

try { // Delete the email identity DeleteEmailIdentityRequest deleteIdentityRequest = DeleteEmailIdentityRequest.builder() .emailIdentity(this.verifiedEmail) .build(); sesClient.deleteEmailIdentity(deleteIdentityRequest); System.out.println("Email identity deleted: " + this.verifiedEmail); } catch (NotFoundException e) { // If the email identity does not exist, log the error and proceed System.out.println("Email identity not found. Skipping deletion..."); } catch (Exception e) { System.err.println("Error occurred while deleting the email identity: " + e.getMessage()); e.printStackTrace(); } } else { System.out.println("Skipping email identity deletion."); }

O código de exemplo a seguir mostra como usar DeleteEmailTemplate.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

try { // Delete the template DeleteEmailTemplateRequest deleteTemplateRequest = DeleteEmailTemplateRequest.builder() .templateName(TEMPLATE_NAME) .build(); sesClient.deleteEmailTemplate(deleteTemplateRequest); System.out.println("Email template deleted: " + TEMPLATE_NAME); } catch (NotFoundException e) { // If the email template does not exist, log the error and proceed System.out.println("Email template not found. Skipping deletion..."); } catch (Exception e) { System.err.println("Error occurred while deleting the email template: " + e.getMessage()); e.printStackTrace(); }

O código de exemplo a seguir mostra como usar ListContacts.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

ListContactsRequest contactListRequest = ListContactsRequest.builder() .contactListName(CONTACT_LIST_NAME) .build(); List<String> contactEmails; try { ListContactsResponse contactListResponse = sesClient.listContacts(contactListRequest); contactEmails = contactListResponse.contacts().stream() .map(Contact::emailAddress) .toList(); } catch (Exception e) { // TODO: Remove when listContacts's GET body issue is resolved. contactEmails = this.contacts; }
  • Para API obter detalhes, consulte ListContactsem AWS SDK for Java 2.x APIReferência.

O código de exemplo a seguir mostra como usar SendEmail.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Envia uma mensagem.

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

Envia uma mensagem usando um modelo.

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 obter detalhes, consulte SendEmailem AWS SDK for Java 2.x APIReferência.

Cenários

O exemplo de código a seguir mostra como executar o fluxo de trabalho do boletim informativo Amazon SES API v2.

SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

try { // 2. Create a contact list String contactListName = CONTACT_LIST_NAME; CreateContactListRequest createContactListRequest = CreateContactListRequest.builder() .contactListName(contactListName) .build(); sesClient.createContactList(createContactListRequest); System.out.println("Contact list created: " + contactListName); } catch (AlreadyExistsException e) { System.out.println("Contact list already exists, skipping creation: weekly-coupons-newsletter"); } catch (LimitExceededException e) { System.err.println("Limit for contact lists has been exceeded."); throw e; } catch (SesV2Exception e) { System.err.println("Error creating contact list: " + e.getMessage()); throw e; } try { // Create a new contact with the provided email address in the CreateContactRequest contactRequest = CreateContactRequest.builder() .contactListName(CONTACT_LIST_NAME) .emailAddress(emailAddress) .build(); sesClient.createContact(contactRequest); contacts.add(emailAddress); System.out.println("Contact created: " + emailAddress); // Send a welcome email to the new contact String welcomeHtml = Files.readString(Paths.get("resources/coupon_newsletter/welcome.html")); String welcomeText = Files.readString(Paths.get("resources/coupon_newsletter/welcome.txt")); SendEmailRequest welcomeEmailRequest = SendEmailRequest.builder() .fromEmailAddress(this.verifiedEmail) .destination(Destination.builder().toAddresses(emailAddress).build()) .content(EmailContent.builder() .simple( Message.builder() .subject(Content.builder().data("Welcome to the Weekly Coupons Newsletter").build()) .body(Body.builder() .text(Content.builder().data(welcomeText).build()) .html(Content.builder().data(welcomeHtml).build()) .build()) .build()) .build()) .build(); SendEmailResponse welcomeEmailResponse = sesClient.sendEmail(welcomeEmailRequest); System.out.println("Welcome email sent: " + welcomeEmailResponse.messageId()); } catch (AlreadyExistsException e) { // If the contact already exists, skip this step for that contact and proceed // with the next contact System.out.println("Contact already exists, skipping creation..."); } catch (Exception e) { System.err.println("Error occurred while processing email address " + emailAddress + ": " + e.getMessage()); throw e; } } ListContactsRequest contactListRequest = ListContactsRequest.builder() .contactListName(CONTACT_LIST_NAME) .build(); List<String> contactEmails; try { ListContactsResponse contactListResponse = sesClient.listContacts(contactListRequest); contactEmails = contactListResponse.contacts().stream() .map(Contact::emailAddress) .toList(); } catch (Exception e) { // TODO: Remove when listContacts's GET body issue is resolved. contactEmails = this.contacts; } 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()); } try { CreateEmailIdentityRequest createEmailIdentityRequest = CreateEmailIdentityRequest.builder() .emailIdentity(verifiedEmail) .build(); sesClient.createEmailIdentity(createEmailIdentityRequest); System.out.println("Email identity created: " + verifiedEmail); } catch (AlreadyExistsException e) { System.out.println("Email identity already exists, skipping creation: " + verifiedEmail); } catch (NotFoundException e) { System.err.println("The provided email address is not verified: " + verifiedEmail); throw e; } catch (LimitExceededException e) { System.err .println("You have reached the limit for email identities. Please remove some identities and try again."); throw e; } catch (SesV2Exception e) { System.err.println("Error creating email identity: " + e.getMessage()); throw e; } try { // Create an email template named "weekly-coupons" String newsletterHtml = loadFile("resources/coupon_newsletter/coupon-newsletter.html"); String newsletterText = loadFile("resources/coupon_newsletter/coupon-newsletter.txt"); CreateEmailTemplateRequest templateRequest = CreateEmailTemplateRequest.builder() .templateName(TEMPLATE_NAME) .templateContent(EmailTemplateContent.builder() .subject("Weekly Coupons Newsletter") .html(newsletterHtml) .text(newsletterText) .build()) .build(); sesClient.createEmailTemplate(templateRequest); System.out.println("Email template created: " + TEMPLATE_NAME); } catch (AlreadyExistsException e) { // If the template already exists, skip this step and proceed with the next // operation System.out.println("Email template already exists, skipping creation..."); } catch (LimitExceededException e) { // If the limit for email templates is exceeded, fail the workflow and inform // the user System.err.println("You have reached the limit for email templates. Please remove some templates and try again."); throw e; } catch (Exception e) { System.err.println("Error occurred while creating email template: " + e.getMessage()); throw e; } try { // Delete the contact list DeleteContactListRequest deleteContactListRequest = DeleteContactListRequest.builder() .contactListName(CONTACT_LIST_NAME) .build(); sesClient.deleteContactList(deleteContactListRequest); System.out.println("Contact list deleted: " + CONTACT_LIST_NAME); } catch (NotFoundException e) { // If the contact list does not exist, log the error and proceed System.out.println("Contact list not found. Skipping deletion..."); } catch (Exception e) { System.err.println("Error occurred while deleting the contact list: " + e.getMessage()); e.printStackTrace(); } try { // Delete the email identity DeleteEmailIdentityRequest deleteIdentityRequest = DeleteEmailIdentityRequest.builder() .emailIdentity(this.verifiedEmail) .build(); sesClient.deleteEmailIdentity(deleteIdentityRequest); System.out.println("Email identity deleted: " + this.verifiedEmail); } catch (NotFoundException e) { // If the email identity does not exist, log the error and proceed System.out.println("Email identity not found. Skipping deletion..."); } catch (Exception e) { System.err.println("Error occurred while deleting the email identity: " + e.getMessage()); e.printStackTrace(); } } else { System.out.println("Skipping email identity deletion."); } try { // Delete the template DeleteEmailTemplateRequest deleteTemplateRequest = DeleteEmailTemplateRequest.builder() .templateName(TEMPLATE_NAME) .build(); sesClient.deleteEmailTemplate(deleteTemplateRequest); System.out.println("Email template deleted: " + TEMPLATE_NAME); } catch (NotFoundException e) { // If the email template does not exist, log the error and proceed System.out.println("Email template not found. Skipping deletion..."); } catch (Exception e) { System.err.println("Error occurred while deleting the email template: " + e.getMessage()); e.printStackTrace(); }