Prerequisites
To get the most out of this guide, you’ll need to:- Create a SendPost Account
- Spring Boot 2.7+
- Java 11+
- Maven or Gradle
- A Sub-Account API Key from your SendPost dashboard
You can find your API keys in your SendPost Dashboard. Make sure to use your Sub-Account API Key for sending emails.
1. Add Dependency
Maven
Add topom.xml:
POM
<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 tobuild.gradle:
Gradle
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'io.sendpost:sendpost-java-sdk:1.1.4'
}
2. Configuration
Add toapplication.properties:
sendpost.api.key=${SENDPOST_API_KEY}
sendpost.from.email=hello@playwithsendpost.io
sendpost.from.name=SendPost
app.url=https://yourapp.com
application.yml:
sendpost:
api:
key: ${SENDPOST_API_KEY}
from:
email: hello@playwithsendpost.io
name: SendPost
app:
url: https://yourapp.com
3. Create Email Service
Createsrc/main/java/com/example/service/EmailService.java:
Java
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
Createsrc/main/java/com/example/controller/EmailController.java:
Java
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
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
@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)
);
}
}
Java
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Make sure your sender email domain is verified in your SendPost account before sending emails.
7. Next Steps
Explore more examples and use cases:Spring Boot Documentation
Learn more about Spring Boot
SendPost Java SDK
View the official SDK on GitHub
Quickstart Example
View a complete working example on GitHub