> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mailbreeze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Java SDK

> Official Java SDK for MailBreeze

## Installation

The Java SDK is hosted on GitHub Packages. You'll need a GitHub token with `read:packages` scope.

### Gradle (Kotlin DSL)

Add to `~/.gradle/gradle.properties`:

```properties theme={null}
gpr.user=YOUR_GITHUB_USERNAME
gpr.key=ghp_YOUR_GITHUB_TOKEN
```

Add to `build.gradle.kts`:

```kotlin theme={null}
repositories {
    mavenCentral()
    maven {
        url = uri("https://maven.pkg.github.com/mailbreeze/mailbreeze-java")
        credentials {
            username = project.findProperty("gpr.user") as String?
            password = project.findProperty("gpr.key") as String?
        }
    }
}

dependencies {
    implementation("com.mailbreeze:mailbreeze-java:0.1.0")
}
```

### Maven

Add to `~/.m2/settings.xml`:

```xml theme={null}
<servers>
    <server>
        <id>github</id>
        <username>YOUR_GITHUB_USERNAME</username>
        <password>YOUR_GITHUB_TOKEN</password>
    </server>
</servers>
```

Add to `pom.xml`:

```xml theme={null}
<repositories>
    <repository>
        <id>github</id>
        <url>https://maven.pkg.github.com/mailbreeze/mailbreeze-java</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>com.mailbreeze</groupId>
        <artifactId>mailbreeze-java</artifactId>
        <version>0.1.0</version>
    </dependency>
</dependencies>
```

## Requirements

* Java 17+
* OkHttp 4.x (included)
* Jackson 2.x (included)

## Quick Start

```java theme={null}
import com.mailbreeze.MailBreeze;
import com.mailbreeze.models.*;

// Initialize the client
MailBreeze mailbreeze = MailBreeze.builder()
    .apiKey(System.getenv("MAILBREEZE_API_KEY"))
    .build();

// Send an email
SendEmailResult result = mailbreeze.emails().send(
    SendEmailParams.builder()
        .from("hello@yourdomain.com")
        .to("user@example.com")
        .subject("Welcome!")
        .html("<h1>Welcome to our platform!</h1>")
        .build()
);

System.out.println("Email sent: " + result.getEmailId());
```

## Configuration

```java theme={null}
MailBreeze mailbreeze = MailBreeze.builder()
    .apiKey("sk_live_xxx")                          // Required
    .baseUrl("https://api.mailbreeze.com")          // Optional: custom API URL
    .timeout(Duration.ofSeconds(30))                 // Optional: request timeout
    .maxRetries(3)                                   // Optional: max retry attempts
    .build();
```

## Resources

### Emails

```java theme={null}
// Send email
SendEmailResult result = mailbreeze.emails().send(
    SendEmailParams.builder()
        .from("hello@yourdomain.com")
        .to("user@example.com")
        .subject("Hello")
        .html("<p>Hello!</p>")
        .build()
);

// Send with idempotency key (prevents duplicate sends)
SendEmailResult result = mailbreeze.emails().send(params, "unique-key-123");

// List emails
PaginatedResponse<Email> emails = mailbreeze.emails().list();

// List with filters
PaginatedResponse<Email> emails = mailbreeze.emails().list(
    ListEmailsParams.builder()
        .status(EmailStatus.DELIVERED)
        .page(1)
        .limit(20)
        .build()
);

// Get email
Email email = mailbreeze.emails().get("msg_xxx");

// Get stats
EmailStats stats = mailbreeze.emails().stats();
```

### Attachments

```java theme={null}
// Step 1: Create upload URL
CreateAttachmentUploadResult upload = mailbreeze.attachments().createUpload(
    CreateAttachmentUploadParams.builder()
        .fileName("report.pdf")
        .contentType("application/pdf")
        .fileSize(1024000L)
        .build()
);

// Step 2: Upload file to the provided URL (use your HTTP client)
// PUT upload.getUploadUrl() with file content

// Step 3: Confirm upload
Attachment attachment = mailbreeze.attachments().confirm(
    ConfirmAttachmentParams.builder()
        .attachmentId(upload.getAttachmentId())
        .uploadToken(upload.getUploadToken())
        .build()
);

// Use attachment ID when sending emails
```

### Lists

```java theme={null}
// Create list
ContactList list = mailbreeze.lists().create(
    CreateListParams.builder()
        .name("Newsletter")
        .description("Main newsletter subscribers")
        .customField(
            CustomFieldDefinition.builder()
                .key("company")
                .label("Company")
                .type(FieldType.TEXT)
                .build()
        )
        .build()
);

// List all
PaginatedResponse<ContactList> lists = mailbreeze.lists().list();

// Get, update, delete
ContactList list = mailbreeze.lists().get("lst_xxx");

mailbreeze.lists().update("lst_xxx",
    UpdateListParams.builder()
        .name("New Name")
        .build()
);

mailbreeze.lists().delete("lst_xxx");

// Get stats
ListStats stats = mailbreeze.lists().stats("lst_xxx");
```

### Contacts

Contacts are scoped to a list. Create a contacts instance by calling `contacts(listId)`:

```java theme={null}
// Get contacts resource for a list
Contacts contacts = mailbreeze.contacts("lst_xxx");

// Create contact
Contact contact = contacts.create(
    CreateContactParams.builder()
        .email("user@example.com")
        .firstName("John")
        .lastName("Doe")
        .customField("company", "Acme Inc")
        .build()
);

// List contacts
PaginatedResponse<Contact> list = contacts.list();

// List with filters
PaginatedResponse<Contact> list = contacts.list(
    ListContactsParams.builder()
        .status(ContactStatus.ACTIVE)
        .page(1)
        .limit(50)
        .build()
);

// Get, update, delete
Contact contact = contacts.get("cnt_xxx");

contacts.update("cnt_xxx",
    UpdateContactParams.builder()
        .firstName("Jane")
        .build()
);

contacts.delete("cnt_xxx");

// Suppress contact
contacts.suppress("cnt_xxx", SuppressReason.UNSUBSCRIBED);
```

### Verification

```java theme={null}
// Verify single email
VerifyEmailResult result = mailbreeze.verification().verify("user@example.com");
if (result.isValid()) {
    System.out.println("Safe to send");
}

// Batch verify
BatchVerifyResult batch = mailbreeze.verification().batch(
    BatchVerifyParams.builder()
        .email("user1@example.com")
        .email("user2@example.com")
        .build()
);

// Poll for results
BatchVerifyResult status = mailbreeze.verification().get(batch.getVerificationId());

// Get stats
VerificationStats stats = mailbreeze.verification().stats();
```

## Error Handling

```java theme={null}
import com.mailbreeze.exceptions.*;

try {
    mailbreeze.emails().send(params);
} catch (ValidationException e) {
    // Invalid parameters (400)
    System.err.println("Validation error: " + e.getMessage());
    System.err.println("Details: " + e.getDetails());
} catch (AuthenticationException e) {
    // Invalid API key (401)
    System.err.println("Auth error: " + e.getMessage());
} catch (NotFoundException e) {
    // Resource not found (404)
    System.err.println("Not found: " + e.getMessage());
} catch (RateLimitException e) {
    // Rate limited (429)
    System.err.println("Rate limited. Retry after: " + e.getRetryAfter() + "s");
} catch (ServerException e) {
    // Server error (5xx) - automatically retried
    System.err.println("Server error: " + e.getMessage());
} catch (MailBreezeException e) {
    // Generic API error
    System.err.println("Code: " + e.getCode());
    System.err.println("Message: " + e.getMessage());
    System.err.println("Status: " + e.getStatusCode());
    System.err.println("Request ID: " + e.getRequestId());
}
```

## Features

* **Builder Pattern** - Fluent API for all parameters
* **Type Safety** - Strongly typed models and enums
* **Automatic Retries** - Exponential backoff for transient failures
* **Idempotency** - Built-in support for idempotency keys
* **79% Test Coverage** - Comprehensive test suite

## Links

<CardGroup cols={2}>
  <Card title="GitHub Packages" icon="github" href="https://github.com/MailBreeze/mailbreeze-java/packages">
    View package
  </Card>

  <Card title="Source Code" icon="code" href="https://github.com/MailBreeze/mailbreeze-java">
    GitHub repository
  </Card>
</CardGroup>
