> ## 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.

# Spring Boot Quickstart

> Learn how to send emails with SendPost in your Spring Boot application using services, REST controllers, and dependency injection

## Prerequisites

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

* [**Create a SendPost Account**](https://app.sendpost.io/register)
* [**Spring Boot 2.7+**](https://spring.io/projects/spring-boot)
* [**Java 11+**](https://www.oracle.com/java/technologies/downloads/)
* [**Maven or Gradle**](https://maven.apache.org/)
* A **Sub-Account API Key** from your SendPost dashboard

<Info>
  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.
</Info>

## 1. Add Dependency

### Maven

Add to `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

Add to `build.gradle`:

```groovy Gradle theme={null}
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'io.sendpost:sendpost-java-sdk:1.1.4'
}
```

## 2. Configuration

Add to `application.properties`:

```properties theme={null}
sendpost.api.key=${SENDPOST_API_KEY}
sendpost.from.email=hello@playwithsendpost.io
sendpost.from.name=SendPost
app.url=https://yourapp.com
```

Or `application.yml`:

```yaml theme={null}
sendpost:
  api:
    key: ${SENDPOST_API_KEY}
  from:
    email: hello@playwithsendpost.io
    name: SendPost
app:
  url: https://yourapp.com
```

## 3. Create Email Service

Create `src/main/java/com/example/service/EmailService.java`:

```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;
    private final String fromEmail;
    private final String fromName;
    private final String appUrl;

    public EmailService(
            @Value("${sendpost.api.key}") String apiKey,
            @Value("${sendpost.from.email}") String fromEmail,
            @Value("${sendpost.from.name}") String fromName,
            @Value("${app.url}") String appUrl) {
        this.apiKey = apiKey;
        this.fromEmail = fromEmail;
        this.fromName = fromName;
        this.appUrl = appUrl;
        
        ApiClient client = Configuration.getDefaultApiClient();
        client.setBasePath("https://api.sendpost.io/api/v1");
        this.emailApi = new EmailApi(client);
    }

    public EmailResponse sendEmail(String to, String subject, String htmlBody, String textBody) {
        try {
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.setSubject(subject);
            emailMessage.setHtmlBody(htmlBody);
            emailMessage.setTextBody(textBody != null ? textBody : htmlBody.replaceAll("<[^>]*>", ""));
            
            From from = new From();
            from.setEmail(fromEmail);
            from.setName(fromName);
            emailMessage.setFrom(from);
            
            To recipient = new To();
            recipient.setEmail(to);
            emailMessage.setTo(Arrays.asList(recipient));
            
            emailMessage.setTrackOpens(true);
            emailMessage.setTrackClicks(true);
            
            List<EmailResponse> result = emailApi.sendEmail(apiKey, emailMessage);
            return result.get(0);
        } catch (ApiException e) {
            throw new RuntimeException("Failed to send email: " + e.getMessage(), e);
        }
    }

    public EmailResponse sendWelcomeEmail(String email, String firstName) {
        try {
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.setSubject("Welcome {{firstName}}!");
            
            From from = new From();
            from.setEmail(fromEmail);
            from.setName(fromName);
            emailMessage.setFrom(from);
            
            To recipient = new To();
            recipient.setEmail(email);
            recipient.setName(firstName);
            
            Map<String, Object> customFields = new HashMap<>();
            customFields.put("firstName", firstName);
            recipient.setCustomFields(customFields);
            
            emailMessage.setTo(Arrays.asList(recipient));
            emailMessage.setHtmlBody(
                "<h1>Welcome, {{firstName}}!</h1>" +
                "<p>Thank you for joining us. We're excited to have you on board.</p>" +
                "<p>Get started by exploring our features:</p>" +
                "<ul><li>Feature 1</li><li>Feature 2</li><li>Feature 3</li></ul>" +
                "<p>If you have any questions, just reply to this email.</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" +
                "Get started by exploring our features:\n" +
                "- Feature 1\n- Feature 2\n- Feature 3\n\n" +
                "If you have any questions, just reply to this email.\n\n" +
                "Unsubscribe: {{unsubscribe}}"
            );
            emailMessage.setGroups(Arrays.asList("welcome"));
            emailMessage.setTrackOpens(true);
            emailMessage.setTrackClicks(true);
            
            List<EmailResponse> result = emailApi.sendEmail(apiKey, emailMessage);
            return result.get(0);
        } catch (ApiException e) {
            throw new RuntimeException("Failed to send welcome email: " + e.getMessage(), e);
        }
    }

    public EmailResponse sendPasswordResetEmail(String email, String resetToken, String firstName) {
        try {
            String resetUrl = appUrl + "/reset-password?token=" + resetToken;
            
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.setSubject("Reset Your Password");
            
            From from = new From();
            from.setEmail(fromEmail);
            from.setName(fromName);
            emailMessage.setFrom(from);
            
            To recipient = new To();
            recipient.setEmail(email);
            recipient.setName(firstName);
            
            Map<String, Object> customFields = new HashMap<>();
            customFields.put("firstName", firstName);
            customFields.put("resetUrl", resetUrl);
            recipient.setCustomFields(customFields);
            
            emailMessage.setTo(Arrays.asList(recipient));
            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);
            
            List<EmailResponse> result = emailApi.sendEmail(apiKey, emailMessage);
            return result.get(0);
        } catch (ApiException e) {
            throw new RuntimeException("Failed to send password reset email: " + e.getMessage(), e);
        }
    }
}
```

## 4. Create REST Controller

Create `src/main/java/com/example/controller/EmailController.java`:

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

import com.example.service.EmailService;
import io.sendpost.client.model.EmailResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/email")
public class EmailController {
    
    @Autowired
    private EmailService emailService;
    
    @PostMapping("/send")
    public ResponseEntity<?> sendEmail(@RequestBody EmailRequest request) {
        try {
            EmailResponse response = emailService.sendEmail(
                request.getTo(),
                request.getSubject(),
                request.getHtmlBody(),
                request.getTextBody()
            );
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("messageId", response.getMessageId());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    @PostMapping("/welcome")
    public ResponseEntity<?> sendWelcomeEmail(@RequestBody WelcomeEmailRequest request) {
        try {
            EmailResponse response = emailService.sendWelcomeEmail(
                request.getEmail(),
                request.getFirstName()
            );
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("messageId", response.getMessageId());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    @PostMapping("/password-reset")
    public ResponseEntity<?> sendPasswordReset(@RequestBody PasswordResetRequest request) {
        try {
            EmailResponse response = emailService.sendPasswordResetEmail(
                request.getEmail(),
                request.getResetToken(),
                request.getFirstName()
            );
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("messageId", response.getMessageId());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("error", e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
}
```

## 5. Request DTOs

Create DTOs:

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

public class EmailRequest {
    private String to;
    private String subject;
    private String htmlBody;
    private String textBody;
    
    // Getters and setters
    public String getTo() { return to; }
    public void setTo(String to) { this.to = to; }
    // ... other getters and setters
}

public class WelcomeEmailRequest {
    private String email;
    private String firstName;
    
    // Getters and setters
}

public class PasswordResetRequest {
    private String email;
    private String resetToken;
    private String firstName;
    
    // Getters and setters
}
```

## 6. Using Async Email Sending

Create async service:

```java Java theme={null}
@Service
public class AsyncEmailService {
    
    @Autowired
    private EmailService emailService;
    
    @Async
    public CompletableFuture<EmailResponse> sendEmailAsync(String to, String subject, String htmlBody) {
        return CompletableFuture.completedFuture(
            emailService.sendEmail(to, subject, htmlBody, null)
        );
    }
}
```

Enable async:

```java Java theme={null}
@SpringBootApplication
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
```

<Warning>
  Make sure your sender email domain is verified in your SendPost account before sending emails.
</Warning>

## 7. Next Steps

Explore more examples and use cases:

<Columns cols={3}>
  <Card title="Spring Boot Documentation" icon="spring" href="https://spring.io/projects/spring-boot">
    Learn more about Spring Boot
  </Card>

  <Card title="SendPost Java SDK" icon="java" href="https://github.com/sendpost/sendpost-java-sdk">
    View the official SDK on GitHub
  </Card>

  <Card title="Quickstart Example" icon="github" href="https://github.com/sendpost/sendpost-spring-boot-example">
    View a complete working example on GitHub
  </Card>
</Columns>
