### Resend Java SDK - Configuration and Setup Source: https://github.com/resend/resend-java/blob/main/_autodocs/GENERATION-SUMMARY.txt Guidance on setting up the Resend Java SDK, including environment variable configuration, HTTP client setup, and application integration examples. ```APIDOC ## Configuration and Setup (`configuration.md`) This section details how to configure and set up the Resend Java SDK for your application. ### Key Topics: - **Environment variable setup**: Instructions for configuring Resend using environment variables. - **HTTP client configuration**: Details on customizing the underlying HTTP client. - **Dependency list**: Information on required libraries and dependencies. - **Performance tuning**: Tips for optimizing SDK performance. - **Security best practices**: Recommendations for secure usage. - **Application setup examples**: Demonstrations for integrating with popular frameworks like Spring Boot and standalone applications. ``` -------------------------------- ### Create API Key with Specific Permissions Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/apikeys-service.md Example of creating an API key with a defined set of permissions for specific operations. ```java CreateApiKeyOptions options = new CreateApiKeyOptions(); options.setName("Mobile App Key"); options.setPermissions(Arrays.asList( "sending:write", "emails:read", "contacts:read", "contacts:write" )); CreateApiKeyResponse response = resend.apiKeys().create(options); // Store the key securely (use environment variables or secrets manager) System.setProperty("MOBILE_APP_API_KEY", response.getToken()); ``` -------------------------------- ### Full Template Workflow Example Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/templates-service.md Demonstrates the complete lifecycle of a template: creation, optional updating, publishing, and subsequent use in sending an email. This covers all essential template management operations. ```java // Step 1: Create template CreateTemplateOptions createOptions = new CreateTemplateOptions(); createOptions.setName("Order Confirmation"); createOptions.setSubject("Your order #{{order_id}} is confirmed"); createOptions.setHtmlPart( "

Order Confirmed

" + "

Hi {{customer_name}},

" + "

Your order {{order_id}} has been received.

" + "

Total: {{total_amount}}

" ); CreateTemplateResponseSuccess created = resend.templates().create(createOptions); String templateId = created.getId(); // Step 2: Update if needed UpdateTemplateOptions updateOptions = new UpdateTemplateOptions(); updateOptions.setHtmlPart("

Order Confirmed

Updated content

"); resend.templates().update(templateId, updateOptions); // Step 3: Publish PublishTemplateResponseSuccess published = resend.templates().publish(templateId); System.out.println("Template published and ready to use"); // Step 4: Use in emails Template template = Template.builder() .id(published.getId()) .addVariable("order_id", "ORD-123456") .addVariable("customer_name", "John Doe") .addVariable("total_amount", "$99.99") .build(); CreateEmailOptions emailOptions = CreateEmailOptions.builder() .from("orders@example.com") .to("john@example.com") .template(template) .build(); CreateEmailResponse emailResponse = resend.emails().send(emailOptions); ``` -------------------------------- ### Create Email Automation Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Example of how to create an email automation using the automations service. Requires a Resend client instance and automation options. ```java CreateAutomationResponseSuccess automation = resend.automations().create(options); ``` -------------------------------- ### List Email Events Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Example of how to list email events using the events service. Requires a Resend client instance. ```java ListEventsResponse events = resend.events().list(); ``` -------------------------------- ### Thread-Safe SDK Usage Example Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/core-utilities.md Demonstrates how to safely use a single `Resend` client instance across multiple threads for concurrent API operations. ```java // Single shared instance Resend resend = new Resend(apiKey); // Safe to use from multiple threads ExecutorService executor = Executors.newFixedThreadPool(10); for (int i = 0; i < 100; i++) { final int index = i; executor.submit(() -> { try { resend.emails().send(createEmailOptions(index)); } catch (ResendException e) { logger.error("Send failed", e); } }); } ``` -------------------------------- ### Manage Template Versions Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/templates-service.md Demonstrates how to get the current template version, duplicate an existing template to create a new version, update the new version's content, and publish it. ```java // Get current template GetTemplateResponseSuccess template = resend.templates().get("tmpl_123"); System.out.println("Version: " + template.getVersion()); // Create a new version by duplicating DuplicateTemplateResponseSuccess copy = resend.templates().duplicate("tmpl_123"); System.out.println("New version created: " + copy.getId()); // Update the copy UpdateTemplateOptions options = new UpdateTemplateOptions(); options.setHtmlPart("

New Version Content

"); resend.templates().update(copy.getId(), options); // Publish when ready resend.templates().publish(copy.getId()); ``` -------------------------------- ### List Email Activity Logs Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Example of how to list email activity logs using the logs service. Requires a Resend client instance. ```java ListLogsResponse logs = resend.logs().list(); ``` -------------------------------- ### get() - Retrieve Template Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/templates-service.md Retrieves a template by its ID or alias. ```APIDOC ## get() - Retrieve Template Retrieves a template by ID or alias. ### Method GET ### Endpoint /templates/{templateId} ### Parameters #### Path Parameters - **templateId** (String) - Required - Template ID or alias ### Response #### Success Response (200) - **id** (String) - The unique identifier of the template. - **name** (String) - The name of the template. - **subject** (String) - The subject of the template, can include variables. - **html_part** (String) - The HTML content of the template. - **text_part** (String) - The plain text content of the template. - **variables** (Object) - An object containing template variables. - **alias** (String) - An optional alias for the template. - **created_at** (String) - The timestamp when the template was created. - **updated_at** (String) - The timestamp when the template was last updated. ### Response Example ```json { "id": "tmpl_abc123", "name": "Welcome Email", "subject": "Welcome {{first_name}}!", "html_part": "

Hello {{first_name}}

Welcome to our service!

", "text_part": "Hello {{first_name}}!\nWelcome to our service!", "variables": {}, "alias": "welcome-email", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:05:00Z" } ``` ``` -------------------------------- ### Resend Constructor Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Initializes the Resend client with your API key. This is the primary way to start using the Resend Java SDK. ```APIDOC ## Resend Constructor ### Description Initializes the Resend client with your API key. This is the primary way to start using the Resend Java SDK. ### Method Signature ```java public Resend(String apiKey) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | apiKey | String | Yes | — | API key from Resend Dashboard for authentication | ``` -------------------------------- ### Resend Java SDK - Overview Source: https://github.com/resend/resend-java/blob/main/_autodocs/GENERATION-SUMMARY.txt This section outlines the structure and content of the Resend Java SDK documentation, guiding users on how to navigate and utilize the provided resources. ```APIDOC ## Resend Java SDK Documentation Structure This documentation is organized to help both new and experienced users effectively leverage the Resend Java SDK. ### For New Users: 1. **00-START-HERE.md**: Begin with this file for a quick introduction and navigation guide. 2. **README.md**: Provides a project overview and quick start examples. 3. **Quick Examples**: Follow the provided examples to get started quickly. 4. **Service Docs**: Reference specific service documentation as needed. ### For Developers: 1. **INDEX.md**: Use this file to locate specific methods. 2. **Service Files**: Navigate to the relevant service file (e.g., `emails-service.md`) for detailed method documentation. 3. **Code Examples**: Copy and adapt the provided code examples. 4. **types.md**: Refer to this file for information on data types. 5. **errors.md**: Consult this file for details on error handling. ### For API Lookup: 1. **INDEX.md**: Find the desired method. 2. **Service File**: Read the detailed documentation for the method. 3. **types.md**: Understand the associated data types. 4. **errors.md**: Learn how to handle potential exceptions. ### For Setup: 1. **configuration.md**: Find instructions for environment setup. 2. **README.md**: Review quick examples for initial setup. 3. **errors.md**: Understand error handling during setup. 4. **Service Docs**: Refer to specific service documentation for implementation details. ``` -------------------------------- ### Resend Java SDK - API Reference Files Source: https://github.com/resend/resend-java/blob/main/_autodocs/GENERATION-SUMMARY.txt Detailed documentation for each service within the Resend Java SDK, including method signatures, code examples, and workflow patterns. ```APIDOC ## API Reference Files The Resend Java SDK provides comprehensive API reference documentation for each service, ensuring clarity and ease of use. ### Available Service Files: - **resend-client.md**: Documentation for the main Resend client. - **emails-service.md**: Documentation for Email operations. - **batch-service.md**: Documentation for Batch email sending. - **contacts-service.md**: Documentation for Contact management. - **domains-service.md**: Documentation for Domain management. - **templates-service.md**: Documentation for Template management. - **apikeys-service.md**: Documentation for API key management. - **core-utilities.md**: Documentation for infrastructure classes. ### Content per Service File: - **Complete method documentation**: Detailed signatures and descriptions for all public methods. - **Real code examples**: Runnable examples demonstrating method usage. - **Workflow patterns**: Guidance on common usage scenarios. - **Related types**: Links to type definitions in `types.md`. - **Error handling per method**: Specific error scenarios and handling strategies for each method. ``` -------------------------------- ### Send Email using Resend Java SDK Source: https://github.com/resend/resend-java/blob/main/README.md This example demonstrates how to send an email using the Resend Java SDK. It includes setting sender, recipients (to, cc, bcc), reply-to, subject, and body. Ensure you have your API key and necessary imports. ```java package com.resend; import com.resend.services.emails.model.*; import com.resend.core.provider.AuthenticationProvider; import com.resend.core.provider.impl.AuthenticationProviderStandard; import com.resend.services.emails.ResendEmails; public class Main { public static void main(String[] args) { Resend resend = new Resend("re_123"); CreateEmailOptions params = CreateEmailOptions.builder() .from("Me ") .to("to@example", "you@example.com") .cc("carbon@example.com", "copy@example.com") .bcc("blind@example.com", "carbon.copy@example.com") .replyTo("reply@example.com", "to@example.com") .text("Hello, world!") .subject("Hello from Java!") .build(); try { CreateEmailResponse data = resend.emails().send(params); System.out.println(data.getId()); } catch (ResendException e) { e.printStackTrace(); } } } ``` -------------------------------- ### List All Email Attachments Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/emails-service.md Lists all attachments for a given email. Use this to get a list of all associated files. ```java public ListAttachmentsResponse listAttachments(String emailId) throws ResendException ``` ```java ListAttachmentsResponse response = resend.emails().listAttachments("email_123"); for (AttachmentResponse att : response.getAttachments()) { System.out.println(att.getFileName()); } ``` -------------------------------- ### Send an Email Source: https://github.com/resend/resend-java/blob/main/_autodocs/00-START-HERE.md Example of sending a single email using the Resend Java SDK. Ensure you have initialized the Resend client with your API key. ```java Resend resend = new Resend("re_123"); CreateEmailOptions options = CreateEmailOptions.builder() .from("sender@example.com") .to("recipient@example.com") .subject("Hello!") .text("Body") .build(); try { CreateEmailResponse response = resend.emails().send(options); System.out.println("Email sent: " + response.getId()); } catch (ResendException e) { System.err.println("Error: " + e.getMessage()); } ``` -------------------------------- ### Example: Handling 404 Not Found Source: https://github.com/resend/resend-java/blob/main/_autodocs/errors.md Illustrates attempting to retrieve a non-existent email ID, which results in a 404 Not Found error. The `ResendException` will report `statusCode: 404` and `errorName: "not_found"`. ```java try { resend.emails().get("nonexistent_email_id"); } catch (ResendException e) { // statusCode: 404 // errorName: "not_found" // message: "Email not found" } ``` -------------------------------- ### Example: Handling 401 Unauthorized (Authentication Error) Source: https://github.com/resend/resend-java/blob/main/_autodocs/errors.md Shows how to trigger a 401 Unauthorized error by using an invalid API key. The `ResendException` will have `statusCode: 401` and `errorName: "authentication_error"`. ```java Resend resend = new Resend("invalid_key_xyz"); try { resend.emails().list(); } catch (ResendException e) { // statusCode: 401 // errorName: "authentication_error" // message: "Unauthorized" } ``` -------------------------------- ### Use Batch API for High Volume Source: https://github.com/resend/resend-java/blob/main/_autodocs/README.md Send emails in batches to handle high volumes efficiently. This example shows how to send 100 emails at a time, up to 1000 total. ```java List batch = new ArrayList<>(); for (int i = 0; i < 1000; i++) { batch.add(createEmail(i)); if (batch.size() == 100) { resend.batch().send(batch); batch.clear(); } } ``` -------------------------------- ### Example: Handling 400 Bad Request (Validation Error) Source: https://github.com/resend/resend-java/blob/main/_autodocs/errors.md Demonstrates sending an email with invalid 'from' address, triggering a 400 Bad Request error. The `ResendException` will contain `statusCode: 400` and `errorName: "validation_error"`. ```java CreateEmailOptions options = CreateEmailOptions.builder() .from("invalid") // Missing domain .to("recipient@example.com") .subject("Test") .text("Body") .build(); try { resend.emails().send(options); } catch (ResendException e) { // statusCode: 400 // errorName: "validation_error" // message: "Invalid email format: invalid" } ``` -------------------------------- ### Handle 500/503 Server Errors with Fallback Source: https://github.com/resend/resend-java/blob/main/_autodocs/errors.md Implement a fallback mechanism for server errors (5xx status codes). This example logs the error and queues the email for a later asynchronous retry. ```java try { resend.emails().send(options); } catch (ResendException e) { if (e.getStatusCode() >= 500) { // Server error - log and retry later logger.error("Server error sending email: " + e.getMessage()); queueForRetry(options); // Store in queue for async retry } else { throw e; // Client error - don't retry } } ``` -------------------------------- ### Emails Service - Get Email Source: https://github.com/resend/resend-java/blob/main/_autodocs/INDEX.md Retrieves the details of a specific email using its ID. ```APIDOC ## get() ### Description Retrieves the details of a specific email. ### Method `get(String emailId)` ### Parameters #### Path Parameters - **emailId** (String) - Required - The ID of the email to retrieve. ``` -------------------------------- ### Initialize Resend Client with API Key from Environment Variable Source: https://github.com/resend/resend-java/blob/main/_autodocs/configuration.md Demonstrates the recommended way to initialize the Resend client by securely retrieving the API key from an environment variable. ```java // ✓ GOOD: Use environment variable Resend resend = new Resend(System.getenv("RESEND_API_KEY")); ``` -------------------------------- ### Domain Verification Workflow Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/domains-service.md Illustrates the typical workflow for setting up a domain, including creation, DNS record retrieval, and verification. It involves creating a domain, fetching its DNS records, configuring them with a DNS provider, waiting for propagation, and then verifying the domain. ```java // Step 1: Create the domain CreateDomainOptions createOptions = new CreateDomainOptions(); createOptions.setDomain("mail.mycompany.com"); CreateDomainResponse createResponse = resend.domains().create(createOptions); // Step 2: Get DNS records and configure them in your DNS provider Domain domain = resend.domains().get(createResponse.getId()); System.out.println("Add these DNS records to your DNS provider:"); for (DnsRecord record : domain.getDnsRecords()) { System.out.println("Type: " + record.getType()); System.out.println("Name: " + record.getName()); System.out.println("Value: " + record.getValue()); } // Step 3: After DNS propagation (typically 15-30 minutes), verify Thread.sleep(5 * 60 * 1000); // Wait 5 minutes VerifyDomainResponse verifyResponse = resend.domains().verify(domain.getId()); if ("success".equals(verifyResponse.getStatus())) { System.out.println("Domain verified successfully!"); } else { System.out.println("Domain verification still pending: " + verifyResponse.getStatus()); } ``` -------------------------------- ### Get HTTP Status Code Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/core-utilities.md Retrieves the integer status code from an HTTP response. ```java public int getCode() ``` -------------------------------- ### get() - Retrieve Email Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/emails-service.md Retrieves the details of a previously sent email using its unique identifier. ```APIDOC ## get() - Retrieve Email ### Description Retrieves the details of a previously sent email using its unique identifier. ### Method ```java public Email get(String emailId) ``` ### Parameters #### Path Parameters - **emailId** (String) - Required - Unique identifier of the email to retrieve #### Query Parameters None #### Request Body None ### Request Example ```java Email email = resend.emails().get("email_123abc"); System.out.println("To: " + email.getTo()); System.out.println("Subject: " + email.getSubject()); System.out.println("Created: " + email.getCreatedAt()); ``` ### Response #### Success Response - **Email** - Complete email details including content, recipients, and metadata #### Response Example (Response structure not detailed in source, only return type is mentioned) ### Throws - **ResendException** - If the email does not exist or request fails ``` -------------------------------- ### Service Instantiation for Operations Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/core-utilities.md Illustrates creating service instances (e.g., `Emails`) on a per-operation basis, highlighting their lightweight and thread-safe nature. ```java // Services are lightweight, safe to create per-operation public void sendEmail(CreateEmailOptions options) throws ResendException { Emails emailsService = resend.emails(); return emailsService.send(options); } ``` -------------------------------- ### Constructor Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/templates-service.md Initializes the Templates service with an API key for authentication. ```APIDOC ## Constructor ```java public Templates(String apiKey) ``` ### Parameters #### Path Parameters - **apiKey** (String) - Required - API key for authentication ``` -------------------------------- ### get() - Retrieve Domain Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/domains-service.md Retrieves details about a specific sending domain using its unique identifier. ```APIDOC ## get() - Retrieve Domain ### Description Retrieves details about a specific sending domain. ### Method GET ### Endpoint /domains/{domain_id} ### Parameters #### Path Parameters - **domain_id** (string) - Required - Unique identifier of the domain ### Response #### Success Response (200) - **id** (string) - The unique identifier for the domain. - **domain** (string) - The domain name. - **status** (string) - The verification status of the domain. - **created_at** (string) - The timestamp when the domain was created. - **dns_records** (object) - DNS records associated with the domain (may be null if verified). #### Response Example ```json { "id": "domain_abc123", "domain": "mail.example.com", "status": "verified", "created_at": "2023-10-27T10:00:00Z", "dns_records": null } ``` ``` -------------------------------- ### Initialize Email Service with API Key Source: https://github.com/resend/resend-java/blob/main/_autodocs/configuration.md Instantiates the Resend client using an API key from environment variables. Throws an exception if the API key is not found. ```java public class EmailService { private final Resend resend; public EmailService() { String apiKey = System.getenv("RESEND_API_KEY"); if (apiKey == null || apiKey.isEmpty()) { throw new IllegalStateException("RESEND_API_KEY environment variable not set"); } this.resend = new Resend(apiKey); } public void sendWelcomeEmail(String recipientEmail) throws ResendException { CreateEmailOptions options = CreateEmailOptions.builder() .from("welcome@myapp.com") .to(recipientEmail) .subject("Welcome!") .text("Thanks for signing up") .build(); resend.emails().send(options); } } ``` -------------------------------- ### Get Resend SDK Version Source: https://github.com/resend/resend-java/blob/main/_autodocs/configuration.md Retrieves the current version of the Resend SDK being used in the project. ```java String version = SdkVersion.getVersion(); System.out.println("Resend SDK Version: " + version); ``` -------------------------------- ### Constructor Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/contacts-service.md Initializes the Contacts service with an API key for authentication. ```APIDOC ## Constructor ### Description Initializes the Contacts service with an API key for authentication. ### Parameters #### Path Parameters - **apiKey** (String) - Required - API key for authentication ``` -------------------------------- ### Emails Service - Get Attachment Source: https://github.com/resend/resend-java/blob/main/_autodocs/INDEX.md Retrieves a single attachment for a given email ID and attachment ID. ```APIDOC ## getAttachment() ### Description Retrieves a single attachment for an email. ### Method `getAttachment(String emailId, String attachmentId)` ### Parameters #### Path Parameters - **emailId** (String) - Required - The ID of the email. - **attachmentId** (String) - Required - The ID of the attachment. ``` -------------------------------- ### Get HTTP Response Body Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/core-utilities.md Retrieves the body of an HTTP response, typically parsed into a specific type. ```java public T getBody() ``` -------------------------------- ### Typical Usage Pattern for Sending Email Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Demonstrates the typical usage pattern for initializing the Resend client and sending a single email. Includes error handling for potential exceptions. ```java // Initialize the client with API key Resend resend = new Resend(System.getenv("RESEND_API_KEY")); // Send a single email CreateEmailOptions emailOptions = CreateEmailOptions.builder() .from("sender@example.com") .to("recipient@example.com") .subject("Hello World") .text("This is a test email") .build(); try { CreateEmailResponse response = resend.emails().send(emailOptions); System.out.println("Email sent with ID: " + response.getId()); } catch (ResendException e) { System.err.println("Failed to send email: " + e.getMessage()); System.err.println("Status code: " + e.getStatusCode()); } ``` -------------------------------- ### Initialize Resend Client with API Key from Secrets Manager Source: https://github.com/resend/resend-java/blob/main/_autodocs/configuration.md Shows how to initialize the Resend client by fetching the API key from a secrets management service. ```java // ✓ GOOD: Use secrets manager Resend resend = new Resend(secretsManager.get("resend.api_key")); ``` -------------------------------- ### Get Audiences Service (Deprecated) Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Returns an Audiences object for audience operations. This method is deprecated and `segments()` should be used instead. ```java @Deprecated public Audiences audiences() ``` -------------------------------- ### ResendMapper writeValue Example Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/core-utilities.md Serializes a Java object into a JSON string using the ResendMapper. This is useful for preparing request bodies. ```java CreateEmailOptions options = CreateEmailOptions.builder().build(); String json = mapper.writeValue(options); // Result: {"from":"...", "to":[...], ...} ``` -------------------------------- ### Initialize Client Source: https://github.com/resend/resend-java/blob/main/_autodocs/README.md Initializes the Resend client using an API key from environment variables. This is the main entry point for interacting with the Resend API. ```APIDOC ## Initialize Client ### Description Initializes the Resend client using an API key from environment variables. This is the main entry point for interacting with the Resend API. ### Method ```java Resend resend = new Resend(System.getenv("RESEND_API_KEY")); ``` ### Parameters - **RESEND_API_KEY** (string) - Required - Your Resend API key, typically set as an environment variable. ``` -------------------------------- ### Initialize Resend Client with Environment Variable Source: https://github.com/resend/resend-java/blob/main/_autodocs/configuration.md Configure the Resend client using the RESEND_API_KEY environment variable for secure API key management. This avoids hardcoding sensitive credentials. ```java Resend resend = new Resend(System.getenv("RESEND_API_KEY")); ``` ```bash # Linux/macOS export RESEND_API_KEY=re_1234567890abcdef ``` ```powershell # Windows (PowerShell) $env:RESEND_API_KEY = "re_1234567890abcdef" ``` ```properties RESEND_API_KEY=re_1234567890abcdef ``` -------------------------------- ### List all email templates Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/templates-service.md Retrieves all email templates associated with the account. This method can be used without any parameters to get an unfiltered list. ```java ListTemplatesResponseSuccess response = resend.templates().list(); for (Template template : response.getData()) { System.out.println(template.getId() + ": " + template.getName()); } ``` -------------------------------- ### Get Automations Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Returns an Automations object for managing email automation workflows. Use this service to create and manage automations. ```java public Automations automations() ``` -------------------------------- ### Project Directory Structure Source: https://github.com/resend/resend-java/blob/main/_autodocs/MANIFEST.md Illustrates the hierarchical organization of the Resend Java client library documentation files. ```text output/ ├── README.md (START HERE) ├── INDEX.md (Navigation) ├── MANIFEST.md (This file) ├── types.md (All type definitions) ├── configuration.md (Setup and configuration) ├── errors.md (Error handling) └── api-reference/ ├── resend-client.md (Main entry point) ├── emails-service.md (Email operations) ├── batch-service.md (Batch email send) ├── contacts-service.md (Contact management) ├── domains-service.md (Domain management) ├── templates-service.md (Template management) ├── apikeys-service.md (API key management) └── core-utilities.md (Infrastructure classes) ``` -------------------------------- ### Get Events Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Returns an Events object for querying email events. Use this service to access email event data. ```java public Events events() ``` -------------------------------- ### Initialize Resend Client with API Key Source: https://github.com/resend/resend-java/blob/main/_autodocs/configuration.md Initialize the Resend client by passing your API key directly to the constructor. Ensure the API key is obtained from your Resend Dashboard. ```java Resend resend = new Resend("your_api_key_here"); ``` -------------------------------- ### Get Logs Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Returns a Logs object for querying email activity logs. Use this service to retrieve log data. ```java public Logs logs() ``` -------------------------------- ### Initialize Batch Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/batch-service.md Instantiate the Batch service with your Resend API key. ```java public Batch(String apiKey) ``` -------------------------------- ### Error Handling Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/domains-service.md Provides examples of how to handle potential `ResendException` errors when interacting with the Domains API, including specific status codes. ```APIDOC ## Error Handling ```java try { resend.domains().verify("domain_123"); } catch (ResendException e) { if (e.getStatusCode() == 404) { System.err.println("Domain not found"); } else if (e.getStatusCode() == 400) { System.err.println("Invalid domain or verification failed: " + e.getMessage()); } else { System.err.println("Error: " + e.getMessage()); } } ``` ``` -------------------------------- ### Initialize Contacts Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/contacts-service.md Instantiate the Contacts service with your API key. This is the entry point for all contacts-related operations. ```java public Contacts(String apiKey) ``` -------------------------------- ### Access Topics Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Get a `Topics` service object for managing email topics, which are used for subscription management. This is for controlling email subscriptions. ```java CreateTopicResponseSuccess topic = resend.topics().create(options); ``` -------------------------------- ### Access Broadcasts Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Get a `Broadcasts` service object for sending broadcast emails to specific contact segments. This is for one-to-many email campaigns. ```java CreateBroadcastResponseSuccess broadcast = resend.broadcasts().create(options); ``` -------------------------------- ### Create and Verify a Domain Source: https://github.com/resend/resend-java/blob/main/_autodocs/README.md Programmatically create a new sending domain and then verify its status. This involves creating the domain first and then calling the verify method. ```java // Create domain CreateDomainResponse response = resend.domains().create( new CreateDomainOptions("mail.example.com") ); // Wait for DNS configuration... // Verify domain VerifyDomainResponse verified = resend.domains().verify(response.getId()); System.out.println("Status: " + verified.getStatus()); ``` -------------------------------- ### Access Contact Properties Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Get a `ContactProperties` service instance to manage custom properties for your contacts. This is useful for advanced contact segmentation. ```java ContactProperties service = resend.contactProperties(); ``` -------------------------------- ### ResendMapper readValue Example Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/core-utilities.md Deserializes a JSON string into a Java object of a specified type using the ResendMapper. This is useful for parsing API responses. ```java String json = "{\"id\":\"email_123\"}"; CreateEmailResponse response = mapper.readValue(json, CreateEmailResponse.class); ``` -------------------------------- ### Create Batch Emails (Alias) Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/batch-service.md Use the `create` method as an alias for `send()` to create and send a batch of emails. It functions identically to the basic `send` method. ```java public CreateBatchEmailsResponse create(List emails) throws ResendException ``` ```java CreateBatchEmailsResponse response = resend.batch().create(emailList); ``` -------------------------------- ### CreateTemplateOptions Configuration Source: https://github.com/resend/resend-java/blob/main/_autodocs/types.md Defines the configuration options for creating a new template, including name, subject, HTML and text parts, and an optional alias. Required fields are name and subject. ```java public class CreateTemplateOptions { private String name; private String subject; private String htmlPart; private String textPart; private String alias; } ``` -------------------------------- ### get(String contactIdOrEmail) Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/contacts-service.md Retrieves a global contact by their unique ID or email address. This method is useful for fetching the complete details of a specific contact. ```APIDOC ## get(String contactIdOrEmail) ### Description Retrieves a global contact by ID or email address. This method is useful for fetching the complete details of a specific contact. ### Method ```java public GetContactResponseSuccess get(String contactIdOrEmail) throws ResendException ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | contactIdOrEmail | String | Yes | — | Contact ID or email address | ### Returns `GetContactResponseSuccess` — Complete contact details ### Throws `ResendException` — If contact not found or retrieval fails ### Example ```java GetContactResponseSuccess contact = resend.contacts().get("john@example.com"); System.out.println("Name: " + contact.getFirstName() + " " + contact.getLastName()); // Or by ID GetContactResponseSuccess contact = resend.contacts().get("contact_123"); ``` ``` -------------------------------- ### list() - List All Templates Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/templates-service.md Retrieves all templates for the account, with support for pagination. ```APIDOC ## list() - List All Templates Retrieves all templates for the account with pagination support. ### Method GET ### Endpoint /templates ### Parameters #### Query Parameters - **limit** (Integer) - Optional - The maximum number of templates to return. - **after** (String) - Optional - The cursor for the next page of results. ### Response #### Success Response (200) - **data** (Array) - A list of template objects. - **id** (String) - The unique identifier of the template. - **name** (String) - The name of the template. - **subject** (String) - The subject of the template. - **html_part** (String) - The HTML content of the template. - **text_part** (String) - The plain text content of the template. - **variables** (Object) - An object containing template variables. - **alias** (String) - An optional alias for the template. - **created_at** (String) - The timestamp when the template was created. - **updated_at** (String) - The timestamp when the template was last updated. - **next_cursor** (String) - The cursor for the next page of results. ### Response Example ```json { "data": [ { "id": "tmpl_abc123", "name": "Welcome Email", "subject": "Welcome {{first_name}}!", "html_part": "

Hello {{first_name}}

Welcome to our service!

", "text_part": "Hello {{first_name}}!\nWelcome to our service!", "variables": {}, "alias": "welcome-email", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:05:00Z" } ], "next_cursor": "cursor_456" } ``` ``` -------------------------------- ### list() - List All API Keys Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/apikeys-service.md Retrieves all API keys for the account, with support for pagination. ```APIDOC ## list() - List All API Keys ### Description Retrieves all API keys for the account, with support for pagination. ### Method GET ### Endpoint /v1/api-keys ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of API keys to return. - **after** (string) - Optional - The ID of the API key to start listing after. - **before** (string) - Optional - The ID of the API key to list before. ### Response #### Success Response (200) - **keys** (array of objects) - A list of API key metadata. Each object contains: - **id** (string) - The unique identifier of the API key. - **name** (string) - The name of the API key. - **status** (string) - The status of the API key (e.g., "active", "revoked"). - **created_at** (string) - The timestamp when the API key was created. ### Response Example ```json { "keys": [ { "id": "key_abc123", "name": "Production API Key", "status": "active", "created_at": "2023-10-26T10:00:00Z" }, { "id": "key_def456", "name": "Test API Key", "status": "active", "created_at": "2023-10-25T09:00:00Z" } ] } ``` ``` -------------------------------- ### Get Contact Topics Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/contacts-service.md Obtain the ContactTopics service for managing contact subscriptions to topics. This service allows for listing topic subscriptions for a given contact. ```java ContactTopics topicsService = resend.contacts().topics(); ListContactTopicsResponse topics = topicsService.list("contact_id"); ``` -------------------------------- ### Get Contact Segments Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/contacts-service.md Retrieve the ContactSegments service to manage contact memberships within segments. Use this to add or remove contacts from specific segments. ```java ContactSegments segmentsService = resend.contacts().segments(); AddContactToSegmentResponseSuccess result = segmentsService.add(options); ``` -------------------------------- ### create() - Create API Key Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/apikeys-service.md Creates a new API key with optional permissions and expiration. The API key token is only shown once at creation and should be stored securely. ```APIDOC ## create() - Create API Key ### Description Creates a new API key with optional permissions and expiration. ### Method POST ### Endpoint /v1/api-keys ### Parameters #### Request Body - **name** (string) - Required - The name of the API key. - **permissions** (array of strings) - Optional - The permissions to grant to the API key. Possible values: "sending", "sending:write", "emails:read", "emails:write", "contacts:read", "contacts:write", "batch:read", "batch:write", "uploads:read", "uploads:write". - **domain_id** (string) - Optional - The ID of the domain to associate with the API key. - **expires_in** (string) - Optional - The expiration time for the API key (e.g., "24h", "7d"). ### Response #### Success Response (200) - **id** (string) - The unique identifier of the API key. - **token** (string) - The generated API key token. This is only shown once. ### Request Example ```json { "name": "Production API Key", "permissions": ["sending", "contacts:read"], "expires_in": "7d" } ``` ### Response Example ```json { "id": "key_abc123", "token": "re ซึ่งเป็นคีย์ลับที่สร้างขึ้นใหม่" } ``` ``` -------------------------------- ### Domain Verification Workflow Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/domains-service.md Illustrates the typical workflow for setting up and verifying a domain with Resend, including creating a domain, configuring DNS records, and verifying the domain. ```APIDOC ## Domain Verification Workflow Typical workflow for setting up a domain: ```java // Step 1: Create the domain CreateDomainOptions createOptions = new CreateDomainOptions(); createOptions.setDomain("mail.mycompany.com"); CreateDomainResponse createResponse = resend.domains().create(createOptions); // Step 2: Get DNS records and configure them in your DNS provider Domain domain = resend.domains().get(createResponse.getId()); System.out.println("Add these DNS records to your DNS provider:"); for (DnsRecord record : domain.getDnsRecords()) { System.out.println("Type: " + record.getType()); System.out.println("Name: " + record.getName()); System.out.println("Value: " + record.getValue()); } // Step 3: After DNS propagation (typically 15-30 minutes), verify Thread.sleep(5 * 60 * 1000); // Wait 5 minutes VerifyDomainResponse verifyResponse = resend.domains().verify(domain.getId()); if ("success".equals(verifyResponse.getStatus())) { System.out.println("Domain verified successfully!"); } else { System.out.println("Domain verification still pending: " + verifyResponse.getStatus()); } ``` ``` -------------------------------- ### CreateApiKeyOptions Source: https://github.com/resend/resend-java/blob/main/_autodocs/types.md Configuration for creating API keys, including a display name and optional permission scopes. ```APIDOC ## CreateApiKeyOptions ### Description Configuration for creating API keys, including a display name and optional permission scopes. ### Fields #### name (String) - Yes - Display name for the key #### permissions (List) - No - Permission scopes ``` -------------------------------- ### Access Batch Email Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/resend-client.md Get a `Batch` service instance for sending multiple emails efficiently in a single request. Supports up to 100 emails per batch. ```java List emails = Arrays.asList(email1, email2, email3); CreateBatchEmailsResponse response = resend.batch().send(emails); ``` -------------------------------- ### Initialize Emails Service Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/emails-service.md Instantiate the Emails service with your Resend API key. ```java public Emails(String apiKey) ``` -------------------------------- ### Template Versioning Operations Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/templates-service.md Demonstrates how to interact with template versions using the Resend Java SDK. This includes fetching the current template, creating a new version by duplicating an existing one, updating the new version's content, and publishing it. ```APIDOC ## Template Versioning Templates are versioned automatically. ### Get current template ```java GetTemplateResponseSuccess template = resend.templates().get("tmpl_123"); System.out.println("Version: " + template.getVersion()); ``` ### Create a new version by duplicating ```java DuplicateTemplateResponseSuccess copy = resend.templates().duplicate("tmpl_123"); System.out.println("New version created: " + copy.getId()); ``` ### Update the copy ```java UpdateTemplateOptions options = new UpdateTemplateOptions(); options.setHtmlPart("

New Version Content

"); resend.templates().update(copy.getId(), options); ``` ### Publish when ready ```java resend.templates().publish(copy.getId()); ``` ``` -------------------------------- ### Use Builder Pattern for Email Options Source: https://github.com/resend/resend-java/blob/main/_autodocs/README.md Construct `CreateEmailOptions` using the builder pattern for clear, chainable, and validated option configurations. ```java // ✓ Good: Clear, chainable, validates on build CreateEmailOptions options = CreateEmailOptions.builder() .from("sender@example.com") .to("recipient@example.com") .subject("Hello") .text("Body") .build(); ``` -------------------------------- ### Handle API Key Creation Errors Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/apikeys-service.md Demonstrates how to catch and handle specific `ResendException` errors that may occur during the API key creation process. This includes handling invalid options, authentication failures, and rate limiting. ```java try { CreateApiKeyResponse response = resend.apiKeys().create(options); } catch (ResendException e) { if (e.getStatusCode() == 400) { System.err.println("Invalid key options: " + e.getMessage()); } else if (e.getStatusCode() == 401) { System.err.println("Authentication failed"); } else if (e.getStatusCode() == 429) { System.err.println("Rate limited - too many keys created recently"); } } ``` -------------------------------- ### Verify a Domain's DNS Configuration Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/domains-service.md Initiate domain verification by checking if the necessary DNS records have been correctly configured. This confirms your domain is ready for sending. ```java VerifyDomainResponse response = resend.domains().verify("domain_123"); System.out.println("Verification status: " + response.getStatus()); ``` -------------------------------- ### List API Keys with Pagination Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/apikeys-service.md Retrieves API keys with pagination support using limit, after, and before parameters. ```java ListParams params = ListParams.builder() .limit(20) .after("cursor_123") .build(); ListApiKeysResponse response = resend.apiKeys().list(params); System.out.println("Retrieved " + response.getKeys().size() + " API keys"); ``` -------------------------------- ### Avoid Hardcoding API Key Source: https://github.com/resend/resend-java/blob/main/_autodocs/configuration.md Illustrates insecure methods of initializing the Resend client by hardcoding the API key directly in the source code or committing it to version control. ```java // ✗ BAD: Hardcode in source Resend resend = new Resend("re_actual_key_12345"); // ✗ BAD: Check into version control // .env file with RESEND_API_KEY=re_12345 ``` -------------------------------- ### BaseService getHttpClient Method Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/core-utilities.md Retrieves the configured HTTP client instance from the BaseService. ```java public IHttpClient getHttpClient() ``` -------------------------------- ### Handle Template Creation Errors Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/templates-service.md Shows how to implement error handling for template creation using a try-catch block to manage specific Resend API exceptions like invalid input, not found, or name conflicts. ```java try { CreateTemplateResponseSuccess template = resend.templates().create(options); } catch (ResendException e) { if (e.getStatusCode() == 400) { System.err.println("Invalid template: " + e.getMessage()); } else if (e.getStatusCode() == 404) { System.err.println("Template not found"); } else if (e.getStatusCode() == 409) { System.err.println("Name already exists"); } } ``` -------------------------------- ### List API Keys by Permissions Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/apikeys-service.md Retrieves a list of API keys and filters them to display keys with 'write' permissions. Ensure you have initialized the Resend client. ```java ListApiKeysResponse response = resend.apiKeys().list(); System.out.println("Keys with write access:"); for (ApiKey key : response.getKeys()) { List permissions = key.getPermissions(); if (permissions != null && permissions.stream() .anyMatch(p -> p.contains("write"))) { System.out.println(" - " + key.getName()); } } ``` -------------------------------- ### Use Templates Source: https://github.com/resend/resend-java/blob/main/_autodocs/README.md Sends an email using a pre-defined template, allowing for dynamic content injection via variables. ```APIDOC ## Use Templates ### Description Sends an email using a pre-defined template, allowing for dynamic content injection via variables. ### Method ```java CreateEmailResponse response = resend.emails().send(options); ``` ### Parameters #### Request Body (`CreateEmailOptions`) - **from** (string) - Required - The sender's email address. - **to** (string) - Required - The recipient's email address. - **template** (Template object) - Required - The template to use. - **id** (string) - Required - The ID of the template. - **variables** (Map) - Optional - Key-value pairs for dynamic content. ### Request Example ```java Template template = Template.builder() .id("tmpl_welcome_123") .addVariable("first_name", "John") .addVariable("company", "ACME Corp") .build(); CreateEmailOptions options = CreateEmailOptions.builder() .from("sender@example.com") .to("john@example.com") .template(template) .build(); ``` ### Response #### Success Response - **id** (string) - The unique identifier for the sent email. ``` -------------------------------- ### IHttpClient.perform (basic) Source: https://github.com/resend/resend-java/blob/main/_autodocs/api-reference/core-utilities.md Performs an HTTP request with the specified details. This is a core method for SDK communication. ```APIDOC ## IHttpClient.perform (basic) ### Description Performs an HTTP request with the specified details. ### Method `public AbstractHttpResponse perform( String path, String apiKey, HttpMethod method, String payload, MediaType mediaType )` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **path** (`String`) - Required - The API endpoint path. - **apiKey** (`String`) - Required - The API key for authentication. - **method** (`HttpMethod`) - Required - The HTTP method (GET, POST, etc.). - **payload** (`String`) - Optional - The request body payload. - **mediaType** (`MediaType`) - Required - The media type of the payload. ```