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

# Java SDK Quickstart

> Learn how to configure and send your first email with SendPost Java SDK

## Prerequisites

To get the most out of this guide, you'll need to:

* [**Create a SendPost Account**](https://app.sendpost.io/register)
* [Install Java 1.8+](https://www.oracle.com/java/technologies/downloads/?er=221886)
* [Install Maven (3.8.3+)/Gradle (7.2+)](https://maven.apache.org/download.cgi)
* A **Sub-Account API Key** from your SendPost dashboard

> [!NOTE]
>
> You can find your API keys in your [SendPost
> Dashboard](https://app.sendpost.io). Make sure to use your Sub-Account API Key
> for sending emails.

## 1. Install

> [!NOTE]
>
> Check [Maven Central](https://central.sonatype.com/artifact/io.sendpost/sendpost-java-sdk) for the latest version.

### Maven Setup

#### Option 1: Standard Maven Project

Add this dependency to your `pom.xml`:

```xml POM theme={null}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <groupId>com.example</groupId>
    <artifactId>sendpost-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>io.sendpost</groupId>
            <artifactId>sendpost-java-sdk</artifactId>
            <version>1.1.4</version>
        </dependency>
    </dependencies>
</project>
```

#### Option 2: Spring Boot with Maven

Add to your `pom.xml`:

```xml POM theme={null}
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>io.sendpost</groupId>
        <artifactId>sendpost-java-sdk</artifactId>
        <version>1.1.4</version>
    </dependency>
</dependencies>
```

### Gradle Setup

#### Option 1: Standard Gradle Project

Add to your `build.gradle`:

```groovy Gradle theme={null}
plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'io.sendpost:sendpost-java-sdk:1.1.4'
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}
```

#### Option 2: Spring Boot with Gradle

Add to your `build.gradle`:

```groovy Gradle theme={null}
plugins {
    id 'org.springframework.boot' version '2.7.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'io.sendpost:sendpost-java-sdk:1.1.4'
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}
```

#### Option 3: Gradle with Kotlin DSL

Add to your `build.gradle.kts`:

```kotlin Kotlin theme={null}
plugins {
    java
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.sendpost:sendpost-java-sdk:1.1.4")
}

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8
}
```

## 2. Getting Started

### Basic Example

```java Java theme={null}
import io.sendpost.client.ApiClient;
import io.sendpost.client.ApiException;
import io.sendpost.client.Configuration;
import io.sendpost.client.api.EmailApi;
import io.sendpost.client.model.*;
import java.util.Arrays;
import java.util.List;

public class SendPostExample {
  public static void main(String[] args) {
    // Configure API client
    ApiClient defaultClient = Configuration.getDefaultApiClient();
    defaultClient.setBasePath("https://api.sendpost.io/api/v1");
    
    EmailApi apiInstance = new EmailApi(defaultClient);
    String apiKey = System.getenv("SENDPOST_API_KEY"); // Sub-Account API Key
    
    // Create email message
    EmailMessage emailMessage = new EmailMessage();
    emailMessage.setSubject("Hello World");
    emailMessage.setHtmlBody("<strong>it works!</strong>");
    emailMessage.setTextBody("it works!");
    
    // Set sender
    From from = new From();
    from.setEmail("hello@playwithsendpost.io");
    from.setName("SendPost");
    emailMessage.setFrom(from);
    
    // Set recipient
    To to = new To();
    to.setEmail("user@example.com");
    emailMessage.setTo(Arrays.asList(to));
    
    // Enable tracking
    emailMessage.setTrackOpens(true);
    emailMessage.setTrackClicks(true);

    try {
      List<EmailResponse> result = apiInstance.sendEmail(apiKey, emailMessage);
      System.out.println("Email sent successfully!");
      System.out.println("Message ID: " + result.get(0).getMessageId());
    } catch (ApiException e) {
      System.err.println("Exception when calling EmailApi#sendEmail");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}
```

### Maven Project Structure

```
sendpost-example/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── com/
                └── example/
                    └── SendPostExample.java
```

**Run with Maven:**

```bash theme={null}
mvn compile exec:java -Dexec.mainClass="com.example.SendPostExample"
```

### Gradle Project Structure

```
sendpost-example/
├── build.gradle
└── src/
    └── main/
        └── java/
            └── com/
                └── example/
                    └── SendPostExample.java
```

**Run with Gradle:**

```bash theme={null}
./gradlew run --main-class=com.example.SendPostExample
```

Or add to `build.gradle`:

```groovy Gradle theme={null}
application {
    mainClass = 'com.example.SendPostExample'
}
```

Then run:

```bash theme={null}
./gradlew run
```

## 3. Common Use Cases

### Welcome Email

```java Java theme={null}
public class WelcomeEmailService {
    private EmailApi emailApi;
    private String apiKey;
    
    public WelcomeEmailService(String apiKey) {
        this.apiKey = apiKey;
        ApiClient client = Configuration.getDefaultApiClient();
        client.setBasePath("https://api.sendpost.io/api/v1");
        this.emailApi = new EmailApi(client);
    }
    
    public void sendWelcomeEmail(String userEmail, String firstName) {
        EmailMessage emailMessage = new EmailMessage();
        emailMessage.setSubject("Welcome {{firstName}}!");
        
        From from = new From();
        from.setEmail("hello@playwithsendpost.io");
        from.setName("SendPost");
        emailMessage.setFrom(from);
        
        To to = new To();
        to.setEmail(userEmail);
        to.setName(firstName);
        
        // Add custom fields for personalization
        Map<String, Object> customFields = new HashMap<>();
        customFields.put("firstName", firstName);
        to.setCustomFields(customFields);
        
        emailMessage.setTo(Arrays.asList(to));
        
        emailMessage.setHtmlBody(
            "<h1>Welcome, {{firstName}}!</h1>" +
            "<p>Thank you for joining us. We're excited to have you on board.</p>" +
            "<p><a href=\"{{unsubscribe}}\">Unsubscribe</a></p>"
        );
        emailMessage.setTextBody(
            "Welcome, {{firstName}}!\n\n" +
            "Thank you for joining us. We're excited to have you on board.\n\n" +
            "Unsubscribe: {{unsubscribe}}"
        );
        emailMessage.setGroups(Arrays.asList("welcome"));
        emailMessage.setTrackOpens(true);
        emailMessage.setTrackClicks(true);
        
        try {
            List<EmailResponse> result = emailApi.sendEmail(apiKey, emailMessage);
            System.out.println("Welcome email sent: " + result.get(0).getMessageId());
        } catch (ApiException e) {
            System.err.println("Error sending welcome email: " + e.getMessage());
        }
    }
}
```

### Password Reset Email

```java Java theme={null}
public class PasswordResetService {
    private EmailApi emailApi;
    private String apiKey;
    
    public void sendPasswordResetEmail(String userEmail, String resetToken, String firstName) {
        String resetUrl = "https://yourapp.com/reset-password?token=" + resetToken;
        
        EmailMessage emailMessage = new EmailMessage();
        emailMessage.setSubject("Reset Your Password");
        
        From from = new From();
        from.setEmail("hello@playwithsendpost.io");
        from.setName("SendPost");
        emailMessage.setFrom(from);
        
        To to = new To();
        to.setEmail(userEmail);
        to.setName(firstName);
        
        Map<String, Object> customFields = new HashMap<>();
        customFields.put("firstName", firstName);
        customFields.put("resetUrl", resetUrl);
        to.setCustomFields(customFields);
        
        emailMessage.setTo(Arrays.asList(to));
        
        emailMessage.setHtmlBody(
            "<h2>Hello {{firstName}},</h2>" +
            "<p>We received a request to reset your password. Click the button below:</p>" +
            "<p><a href=\"{{resetUrl}}\" style=\"background-color: #5750EC; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; display: inline-block;\">Reset Password</a></p>" +
            "<p>Or copy and paste this link: {{resetUrl}}</p>" +
            "<p>This link will expire in 1 hour.</p>"
        );
        emailMessage.setGroups(Arrays.asList("password-reset"));
        emailMessage.setTrackClicks(true);
        
        try {
            emailApi.sendEmail(apiKey, emailMessage);
        } catch (ApiException e) {
            System.err.println("Error sending password reset email: " + e.getMessage());
        }
    }
}
```

## 4. Spring Boot Integration

### Create Email Service

```java Java theme={null}
package com.example.service;

import io.sendpost.client.ApiClient;
import io.sendpost.client.ApiException;
import io.sendpost.client.Configuration;
import io.sendpost.client.api.EmailApi;
import io.sendpost.client.model.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmailService {
    private final EmailApi emailApi;
    private final String apiKey;
    
    public EmailService(@Value("${sendpost.api.key}") String apiKey) {
        this.apiKey = apiKey;
        ApiClient client = Configuration.getDefaultApiClient();
        client.setBasePath("https://api.sendpost.io/api/v1");
        this.emailApi = new EmailApi(client);
    }
    
    public void sendEmail(String to, String subject, String htmlBody, String textBody) {
        EmailMessage emailMessage = new EmailMessage();
        emailMessage.setSubject(subject);
        emailMessage.setHtmlBody(htmlBody);
        emailMessage.setTextBody(textBody);
        
        From from = new From();
        from.setEmail("hello@playwithsendpost.io");
        from.setName("SendPost");
        emailMessage.setFrom(from);
        
        To recipient = new To();
        recipient.setEmail(to);
        emailMessage.setTo(Arrays.asList(recipient));
        
        try {
            emailApi.sendEmail(apiKey, emailMessage);
        } catch (ApiException e) {
            throw new RuntimeException("Failed to send email", e);
        }
    }
}
```

### Add Configuration

Add to `application.properties`:

```properties theme={null}
sendpost.api.key=${SENDPOST_API_KEY}
```

Or `application.yml`:

```yaml theme={null}
sendpost:
  api:
    key: ${SENDPOST_API_KEY}
```

### Use in Controller

```java Java theme={null}
@RestController
@RequestMapping("/api/email")
public class EmailController {
    private final EmailService emailService;
    
    public EmailController(EmailService emailService) {
        this.emailService = emailService;
    }
    
    @PostMapping("/send")
    public ResponseEntity<?> sendEmail(@RequestBody EmailRequest request) {
        try {
            emailService.sendEmail(
                request.getTo(),
                request.getSubject(),
                request.getHtmlBody(),
                request.getTextBody()
            );
            return ResponseEntity.ok().body(Map.of("success", true));
        } catch (Exception e) {
            return ResponseEntity.status(500)
                .body(Map.of("success", false, "error", e.getMessage()));
        }
    }
}
```

> [!WARNING]
>
> Make sure your sender email domain is verified in your SendPost account before
> sending emails.

## 5. Next Steps

Explore more examples and use cases:

> [card] [Java SDK](https://github.com/sendpost/sendpost-java-sdk)
>
> View the official SDK on GitHub

> [card] [SDK Examples](https://github.com/sendpost/sendpost-examples-java)
>
> Comprehensive email sending examples

> [card] [ESP Workflow Example](https://github.com/sendpost/java-esp-example)
>
> Full-featured example app with comprehensive ESP workflow


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.