使用 SDK for Java 2.x 的 Amazon SES API v2 示例 - AWS SDK for Java 2.x

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 SDK for Java 2.x 的 Amazon SES API v2 示例

下列程式碼範例說明如何使用 Amazon SES API v2 來執行動作和實作常見案例。 AWS SDK for Java 2.x

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境和跨服務範例中查看內容中的動作。

Scenarios (案例) 是向您展示如何呼叫相同服務中的多個函數來完成特定任務的程式碼範例。

每個範例都包含一個連結 GitHub,您可以在其中找到如何在內容中設定和執行程式碼的指示。

動作

下列程式碼範例會示範如何使用CreateContact

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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; } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考CreateContact中的。

下列程式碼範例會示範如何使用CreateContactList

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考CreateContactList中的。

下列程式碼範例會示範如何使用CreateEmailIdentity

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考CreateEmailIdentity中的。

下列程式碼範例會示範如何使用CreateEmailTemplate

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考CreateEmailTemplate中的。

下列程式碼範例會示範如何使用DeleteContactList

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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(); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考DeleteContactList中的。

下列程式碼範例會示範如何使用DeleteEmailIdentity

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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."); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考DeleteEmailIdentity中的。

下列程式碼範例會示範如何使用DeleteEmailTemplate

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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(); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考DeleteEmailTemplate中的。

下列程式碼範例會示範如何使用ListContacts

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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; }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考ListContacts中的。

下列程式碼範例會示範如何使用SendEmail

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

傳送訊息。

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

使用範本傳送訊息。

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()); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考SendEmail中的。

案例

下列程式碼範例顯示如何使用 Amazon SES API v2 電子報工作流程。

適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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