SDK for SES API Java 2.x を使用した Amazon v2 の例 - AWS SDK for Java 2.x

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

SDK for SES API Java 2.x を使用した Amazon v2 の例

次のコード例は、Amazon v2 AWS SDK for Java 2.x で SES API を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。ここでは GitHub、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

アクション

次の例は、CreateContact を使用する方法を説明しています。

SDK for Java 2.x
注記

については、「」を参照してください 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 詳細については、「 リファレンスCreateContact」の「」を参照してください。 AWS SDK for Java 2.x API

次の例は、CreateContactList を使用する方法を説明しています。

SDK for Java 2.x
注記

については、「」を参照してください 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 詳細については、「 リファレンスCreateContactList」の「」を参照してください。 AWS SDK for Java 2.x API

次の例は、CreateEmailIdentity を使用する方法を説明しています。

SDK for Java 2.x
注記

については、「」を参照してください 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 詳細については、「 リファレンスCreateEmailIdentity」の「」を参照してください。 AWS SDK for Java 2.x API

次の例は、CreateEmailTemplate を使用する方法を説明しています。

SDK for Java 2.x
注記

については、「」を参照してください 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 詳細については、「 リファレンスCreateEmailTemplate」の「」を参照してください。 AWS SDK for Java 2.x API

次の例は、DeleteContactList を使用する方法を説明しています。

SDK for Java 2.x
注記

については、「」を参照してください 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 詳細については、「 リファレンスDeleteContactList」の「」を参照してください。 AWS SDK for Java 2.x API

次の例は、DeleteEmailIdentity を使用する方法を説明しています。

SDK for Java 2.x
注記

については、「」を参照してください 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 詳細については、「 リファレンスDeleteEmailIdentity」の「」を参照してください。 AWS SDK for Java 2.x API

次の例は、DeleteEmailTemplate を使用する方法を説明しています。

SDK for Java 2.x
注記

については、「」を参照してください 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 詳細については、「 リファレンスDeleteEmailTemplate」の「」を参照してください。 AWS SDK for Java 2.x API

次の例は、ListContacts を使用する方法を説明しています。

SDK for Java 2.x
注記

については、「」を参照してください 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 詳細については、「 リファレンスListContacts」の「」を参照してください。 AWS SDK for Java 2.x API

次の例は、SendEmail を使用する方法を説明しています。

SDK for Java 2.x
注記

については、「」を参照してください 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 詳細については、「 リファレンスSendEmail」の「」を参照してください。 AWS SDK for Java 2.x API

シナリオ

次のコード例は、Amazon v2 SES API ニュースレターワークフローを実行する方法を示しています。

SDK for Java 2.x
注記

については、「」を参照してください 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(); }