Java SDK
Send emails with Java using the official Laneful Java SDK. Built for modern Java applications with comprehensive features and type safety.
Templates, attachments, tracking, webhooks
Built-in validation & error handling
Java 21+ with builder pattern
On this page
Prerequisites
To get the most out of this guide, you'll need:
- • Java 21 or higher
- • Maven or Gradle
- • A Laneful account with API key
- • Verified domain for sending emails
Installation
Maven
Add the following dependency to your pom.xml:
<dependency>
<groupId>com.laneful</groupId>
<artifactId>laneful-java</artifactId>
<version>1.3.0</version>
</dependency>Gradle
Add the following to the dependencies block of your build.gradle or build.gradle.kts:
implementation("com.laneful:laneful-java:1.3.0")This page describes version 1.3.0. Use 1.2.0 or later for webhooks: earlier versions reject payloads that contain a request event. Version 1.3.0 adds the idempotency key, keeps every webhook field and event type, accepts the empty lane_id on request events, and fixes sends to addresses without a name, which the API rejected in 1.2.0.
Quick Start
Send your first email in minutes:
Send Simple Text Email
import com.laneful.client.LanefulClient;
import com.laneful.models.Email;
import com.laneful.models.Address;
import com.laneful.exceptions.*;
import java.util.Map;
public class Main {
public static void main(String[] args) {
try {
// Create client
LanefulClient client = new LanefulClient(
"https://your-endpoint.z1.send.laneful.net",
"your-auth-token"
);
// Create email
Email email = new Email.Builder()
.from(new Address("sender@example.com", "Your Name"))
.to(new Address("recipient@example.com", "Recipient Name"))
.subject("Hello from Laneful!")
.textContent("This is a simple test email sent using the Laneful Java SDK.")
.build();
// Send email
Map<String, Object> response = client.sendEmail(email);
System.out.println("✓ Email sent successfully!");
System.out.println("Response: " + response);
} catch (ValidationException e) {
System.err.println("✗ Validation error: " + e.getMessage());
} catch (ApiException e) {
System.err.println("✗ API error: " + e.getMessage());
System.err.println("Status code: " + e.getStatusCode());
} catch (HttpException e) {
System.err.println("✗ HTTP error: " + e.getMessage());
} catch (Exception e) {
System.err.println("✗ Unexpected error: " + e.getMessage());
}
}
}Replace https://your-endpoint.z1.send.laneful.net with your organization's own HTTP API endpoint and your-auth-token with an API key, both available in the dashboard under Workspaces → Workspace Settings → API Keys (see Sending Email). The API is HTTPS-only.
Examples
Common use cases and patterns. Each email snippet drops into the try block from Quick Start in place of its email creation and sending, so client and the SDK's checked exceptions are already taken care of:
HTML Email with Tracking
import com.laneful.models.TrackingSettings;
// Create tracking settings
TrackingSettings tracking = new TrackingSettings(true, true, true);
Email email = new Email.Builder()
.from(new Address("sender@example.com", "Your Name"))
.to(new Address("recipient@example.com", "Recipient Name"))
.subject("HTML Email with Tracking")
.htmlContent("<h1>Welcome!</h1><p>This is an <strong>HTML email</strong> with tracking enabled.</p>")
.textContent("Welcome! This is an HTML email with tracking enabled.")
.tracking(tracking)
.tag("welcome-email")
.build();
Map<String, Object> response = client.sendEmail(email);Template Email
Email email = new Email.Builder()
.from(new Address("sender@example.com"))
.to(new Address("user@example.com"))
.subject("Welcome to Acme")
.templateId("welcome-template")
.templateData(Map.of(
"name", "John Doe",
"company", "Acme Corporation",
"activation_link", "https://example.com/activate"
))
.build();
Map<String, Object> response = client.sendEmail(email);Email with Attachments
import com.laneful.models.Attachment;
import java.nio.file.Paths;
// Create attachment from file
Attachment attachment = Attachment.fromFile(Paths.get("/path/to/document.pdf"));
Email email = new Email.Builder()
.from(new Address("sender@example.com"))
.to(new Address("user@example.com"))
.subject("Document Attached")
.textContent("Please find the document attached.")
.attachment(attachment)
.build();
Map<String, Object> response = client.sendEmail(email);Multiple Recipients with Reply-To
Email email = new Email.Builder()
.from(new Address("sender@example.com", "Your Name"))
.to(new Address("user1@example.com", "User One"))
.to(new Address("user2@example.com", "User Two"))
.cc(new Address("cc@example.com", "CC Recipient"))
.bcc(new Address("bcc@example.com", "BCC Recipient"))
.replyTo(new Address("reply@example.com", "Reply To"))
.subject("Email to Multiple Recipients")
.textContent("This email is being sent to multiple recipients.")
.build();
Map<String, Object> response = client.sendEmail(email);Scheduled Email
import java.time.Instant;
// Schedule for 24 hours from now
long sendTime = Instant.now().plusSeconds(24 * 60 * 60).getEpochSecond();
Email email = new Email.Builder()
.from(new Address("sender@example.com"))
.to(new Address("user@example.com"))
.subject("Scheduled Email")
.textContent("This email was scheduled.")
.sendTime(sendTime)
.build();
Map<String, Object> response = client.sendEmail(email);Batch Email Sending
import java.util.List;
List<Email> emails = List.of(
new Email.Builder()
.from(new Address("sender@example.com"))
.to(new Address("user1@example.com"))
.subject("Email 1")
.textContent("First email content.")
.build(),
new Email.Builder()
.from(new Address("sender@example.com"))
.to(new Address("user2@example.com"))
.subject("Email 2")
.textContent("Second email content.")
.build()
);
Map<String, Object> response = client.sendEmails(emails);Webhook Handler Example
import com.laneful.webhooks.WebhookVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.Objects;
// Complete webhook handler implementation (Spring Boot)
@RestController
public class WebhookController {
private static final Logger logger = LoggerFactory.getLogger(WebhookController.class);
private final String webhookSecret = Objects.requireNonNull(
System.getenv("LANEFUL_WEBHOOK_SECRET"), "LANEFUL_WEBHOOK_SECRET is required");
@PostMapping("/webhook")
public ResponseEntity<String> handleWebhook(
@RequestBody String payload, // raw request body
@RequestHeader(value = "X-Webhook-Signature", required = false) String signature) {
if (signature == null) {
return ResponseEntity.status(401).body("Missing signature");
}
try {
// Verify signature over the raw body
if (!WebhookVerifier.verifySignature(webhookSecret, payload, signature)) {
return ResponseEntity.status(401).body("Invalid signature");
}
// Parse and validate payload
WebhookVerifier.WebhookData webhookData = WebhookVerifier.parseWebhookPayload(payload);
// Process events
for (Map<String, Object> event : webhookData.getEvents()) {
String eventType = (String) event.get("event");
String email = (String) event.get("email");
switch (eventType) {
case "request":
logger.info("Email accepted for: " + email);
break;
case "delivery":
logger.info("Email delivered to: " + email);
break;
case "open":
logger.info("Email opened by: " + email);
break;
case "click":
String url = (String) event.get("url");
logger.info("Link clicked by " + email + ": " + url);
break;
case "bounce":
boolean isHard = Boolean.TRUE.equals(event.get("is_hard"));
logger.info("Email bounced (" + (isHard ? "hard" : "soft") + ") for: " + email);
break;
}
}
return ResponseEntity.ok("Webhook processed successfully");
} catch (IllegalArgumentException e) {
return ResponseEntity.status(400).body("Invalid payload: " + e.getMessage());
} catch (Exception e) {
logger.error("Webhook processing failed", e);
return ResponseEntity.status(500).body("Processing error");
}
}
}API Reference
LanefulClient
Constructors
- •
LanefulClient(String baseUrl, String authToken)- Default timeout (30 seconds) - •
LanefulClient(String baseUrl, String authToken, Duration timeout)- Custom timeout - •
LanefulClient(String baseUrl, String authToken, Duration timeout, OkHttpClient httpClient)- Custom HTTP client, used as is: its own timeout settings apply instead oftimeout
Every constructor validates its arguments up front and throws ValidationException if the URL or token is empty.
Methods
- •
Map<String, Object> sendEmail(Email email)- Send single email - •
Map<String, Object> sendEmail(Email email, MailSettings settings)- Send single email with mail settings - •
Map<String, Object> sendEmails(List<Email> emails)- Send multiple emails in one request - •
Map<String, Object> sendEmails(List<Email> emails, MailSettings settings)- Send multiple emails with mail settings
Each send method returns the parsed API response: status, plus message_ids (a list) when returnMessageIds is set. Failures surface as typed exceptions: ValidationException, ApiException and HttpException.
Email.Builder
Required Fields
- •
from(Address from)- Sender address - •
subject(String subject)- Email subject. Always set it, also for template emails: the API requires a subject, andbuild()leaves that check to the API - • At least one recipient (
to,ccorbcc) and content (textContent,htmlContentortemplateId).build()checks both for you and throwsValidationExceptionif either is missing
Optional Fields
- •
to(Address to)- Recipient addresses - •
cc(Address cc)- CC recipient addresses - •
bcc(Address bcc)- BCC recipient addresses - •
replyTo(Address replyTo)- Reply-to address - •
fromHeader(Address fromHeader)- Address for the visible From header, if it should differ fromfrom - •
textContent(String textContent)- Plain text content - •
htmlContent(String htmlContent)- HTML content - •
templateId(String templateId)- Template ID - •
templateData(Map<String, Object> templateData)- Template data - •
attachment(Attachment attachment)- File attachments - •
headers(Map<String, String> headers)- Custom email headers. Set From, To, Cc, Bcc, Reply-To and Subject with the builder methods and let Laneful generate the Message-ID; header entries for these are ignored (see Sending Email) - •
sendTime(Long sendTime)- Schedule the send up to 72 hours ahead (Unix seconds, in the future) - •
webhookData(Map<String, String> webhookData)- Your own data, returned unchanged asmetadataon every webhook event for this email: up to 20 keys (up to 50 bytes in UTF-8) with string values (up to 100 bytes) - •
tracking(TrackingSettings tracking)- Email tracking configuration - •
tag(String tag)- Email tag for categorization
fromHeader, to, cc, bcc and replyTo also take plain strings: (String email) or (String email, String name). Field details: Sending Email.
Utility Classes
- •
Address(String email, String name)- Email address with optional name (orAddress(String email)). Validates the address on creation and throwsIllegalArgumentExceptionif it's empty or malformed - •
Attachment.fromFile(Path path)- Create attachment from file (throwsIOException) - •
Attachment(String filename, String contentType, String content, String inlineId)- Create attachment from data:contentis the Base64-encoded file,inlineIdis optional (a three-argument constructor omits it) - •
TrackingSettings(boolean opens, boolean clicks, boolean unsubscribes)- Email tracking configuration (opens, clicks, unsubscribes). A five-argument constructor addsLong unsubscribeGroupIdandString unsubscribeGroupName. Tracking is on by default: withouttracking(...), the API tracks opens, clicks and unsubscribes. With it, all three flags are sent as given, sofalseturns that tracking off - •
MailSettings(Boolean sandboxMode, Boolean returnMessageIds, String idempotencyKey)- Request-level settings for the send methods; passnullto leave a setting out (a two-argument constructor andnew MailSettings().withIdempotencyKey(key)also exist).returnMessageIdsaddsmessage_idsto the response, one per email, each matching themessage_idon that email's webhook events (every email must then have exactly one recipient).sandboxModeaccepts the request without sending it, a safe way to check that your client can reach the API.idempotencyKey(1 to 36 bytes, 1.3.0 and later) prevents duplicate sends, see Error Handling
WebhookVerifier
Signature Verification
- •
boolean verifySignature(String secret, String payload, String signature)- Verifies theX-Webhook-Signaturevalue (bare hex, as Laneful sends it, or with asha256=prefix) against the raw request body. Returns false for a missing signature and throwsIllegalArgumentExceptionif the secret or payload is empty - •
String generateSignature(String secret, String payload)- Generates signature for payload - •
String generateSignature(String secret, String payload, boolean includePrefix)- Generates signature with optional prefix
Payload Processing
- •
WebhookData parseWebhookPayload(String payload)- Parse and validate webhook payload structure. ThrowsIllegalArgumentExceptionfor invalid JSON or a missing or malformed required field. From 1.3.0, events of unknown types are kept; earlier versions reject the whole payload - •
String getSignatureHeaderName()- Get the correct header name for webhook signatures - •
String extractSignatureFromHeaders(Map<String, String> headers)- Extract signature from HTTP headers. Prefer your framework's case-insensitive lookup, such as@RequestHeader("X-Webhook-Signature"): this method matches only the exact keysx-webhook-signature,X_WEBHOOK_SIGNATUREandHTTP_X_WEBHOOK_SIGNATURE, so a map keyedX-Webhook-Signaturereturns null
WebhookData
- •
boolean isBatch()- Returns true if the payload is a JSON array (batch mode), even with a single event - •
List<Map<String, Object>> getEvents()- Returns list of parsed events
Each event map holds every field Laneful sends: id, event, email, message_id, lane_id (empty on request events), tag, timestamp, metadata (the webhookData sent with the email) and the event-specific fields such as url, is_hard, classification and mx_host. event, email, lane_id, message_id, timestamp, tag, url, text, reason, unsubscribe_group_id and the client_* fields are strings; the others keep their JSON types. Use id to skip events you have already processed. Before 1.3.0 the map held only a fixed subset, without id or mx_host. All fields: Webhooks.
Organization API Methods
- • Unsubscribe groups:
listUnsubscribeGroups(long workspaceId, ...),createUnsubscribeGroup(long workspaceId, ...),updateUnsubscribeGroup(long workspaceId, long unsubscribeGroupId, ...) - • Domains:
listDomains(long workspaceId, ...),getDomain(long workspaceId, String domain),createDomain(long workspaceId, ...),updateDomain(long workspaceId, String domain, ...),verifyDomain(long workspaceId, String domain),deleteDomain(long workspaceId, String domain) - • Analytics:
listDomainSpamRatioRadar,listGooglePostmasterSpamReports,listSndsReports
These methods call the Organization API, so create a separate client with base URL https://api.laneful.net and an Organization API key (see Organization API). Domain and unsubscribe group methods are scoped to a workspace and take long workspaceId as their first argument (the API routes them under /v1/workspaces/{workspace_id}/...).
Error Handling
Comprehensive error handling with specific exception types:
import com.laneful.exceptions.*;
try {
Map<String, Object> response = client.sendEmail(email);
System.out.println("✓ Email sent successfully!");
System.out.println("Response: " + response);
} catch (ValidationException e) {
// Invalid input data
System.err.println("✗ Validation error: " + e.getMessage());
System.err.println("Please check your email configuration");
} catch (ApiException e) {
// API returned an error
System.err.println("✗ API error: " + e.getMessage());
System.err.println(" Status code: " + e.getStatusCode());
System.err.println(" Error message: " + e.getErrorMessage());
System.err.println("Please check your API credentials and endpoint");
} catch (HttpException e) {
// Network or HTTP-level error
System.err.println("✗ HTTP error: " + e.getMessage());
System.err.println(" Status code: " + e.getStatusCode());
System.err.println("Please check your network connection and endpoint URL");
} catch (Exception e) {
// Other unexpected errors
System.err.println("✗ Unexpected error: " + e.getMessage());
e.printStackTrace();
}Exception Types
- •
ValidationException- Input validation fails (client constructors,build(), send methods).AddressandAttachmentthrowIllegalArgumentExceptioninstead - •
ApiException- API returns error response
Methods: getStatusCode(), getErrorMessage() - •
HttpException- HTTP communication fails (status code 0 for network errors and timeouts), the endpoint returns 404, or the response isn't JSON
Methods: getStatusCode() - •
LanefulException- Base exception class
Best Practices
- • Always wrap API calls in try-catch
- • Handle specific exception types first
- • Log errors with context information
- • The SDK leaves retries to you (OkHttp may still retry a failed connection on its own). A send that timed out may already have been accepted, so when you retry it, reuse the same idempotency key (see below)
Duplicate Send Protection
Pass an idempotency key (1 to 36 bytes, see Sending Email) and reuse it when you retry a send, for example after a timeout:
Map<String, Object> response = client.sendEmail(
email,
new MailSettings().withIdempotencyKey("order-" + orderId + "-receipt")
);Laneful remembers a key per organization for one hour. A repeated request with the same key returns status accepted with no message IDs and sends nothing, even if the emails differ, so use a new key for every distinct send. Detection is best effort. A request that fails with HTTP 500 doesn't keep its key, so a retry with it is processed as a new request: before resending after a 500, check your webhook events (a request event means Laneful accepted the email). Sandbox mode requests aren't deduplicated. A key outside 1 to 36 bytes throws IllegalArgumentException. Requires 1.3.0 or later.
Webhook Handling
Comprehensive webhook handling with signature verification, payload parsing, and validation:
- • Pass
verifySignaturethe body exactly as received, before parsing it. Laneful signs that raw body with HMAC-SHA256, keyed with your webhook secret, and sends the lowercase hex digest, with no prefix, inX-Webhook-Signature, so re-serialized JSON won't match.verifySignaturealso accepts asha256=prefix. - • Return a 2xx within 30 seconds to acknowledge each webhook call; Laneful automatically retries any other outcome for up to 24 hours. Reserve 401 for an invalid signature and 400 for a payload that fails to parse, and answer 5xx if your handler fails.
- • Use the default Laneful webhook format with
parseWebhookPayload; it reads that format rather than the Mailgun or SendGrid formats.
Basic Signature Verification
import com.laneful.webhooks.WebhookVerifier;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
// In your webhook handler (here a plain servlet)
public class WebhookServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Get the raw request body
String payload = new String(request.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
String signature = request.getHeader("X-Webhook-Signature");
String secret = "your-webhook-secret";
if (!WebhookVerifier.verifySignature(secret, payload, signature)) {
// Invalid signature
response.setStatus(401);
return;
}
try {
// Process webhook data
WebhookVerifier.WebhookData webhookData = WebhookVerifier.parseWebhookPayload(payload);
// Handle webhook events
} catch (IllegalArgumentException e) {
// Not a valid Laneful payload
response.setStatus(400);
}
}
}Advanced Webhook Processing
import com.laneful.webhooks.WebhookVerifier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.Objects;
// Complete webhook verification and processing workflow
@RestController
public class LanefulWebhookController {
private final String webhookSecret = Objects.requireNonNull(
System.getenv("LANEFUL_WEBHOOK_SECRET"), "LANEFUL_WEBHOOK_SECRET is required");
// Step 1: Get the raw payload and the signature header
@PostMapping("/webhooks/laneful")
public ResponseEntity<Void> receive(
@RequestBody String payload,
@RequestHeader(value = "X-Webhook-Signature", required = false) String signature) {
// Step 2: Verify signature over the raw payload
if (!WebhookVerifier.verifySignature(webhookSecret, payload, signature)) {
return ResponseEntity.status(401).build();
}
// Step 3: Parse and validate payload structure
WebhookVerifier.WebhookData webhookData;
try {
webhookData = WebhookVerifier.parseWebhookPayload(payload);
} catch (IllegalArgumentException e) {
return ResponseEntity.status(400).build();
}
// Step 4: Process events (handles both batch and single event formats).
// An exception thrown here makes Spring answer 500, so Laneful retries the request.
for (Map<String, Object> event : webhookData.getEvents()) {
String eventType = (String) event.get("event");
switch (eventType) {
case "request":
handleRequestEvent(event);
break;
case "delivery":
handleDeliveryEvent(event);
break;
case "open":
handleOpenEvent(event);
break;
case "click":
handleClickEvent(event);
break;
case "bounce":
handleBounceEvent(event);
break;
case "drop":
handleDropEvent(event);
break;
case "spam_complaint":
handleSpamComplaintEvent(event);
break;
case "unsubscribe":
handleUnsubscribeEvent(event);
break;
}
}
// Step 5: Acknowledge
return ResponseEntity.ok().build();
}
// Your event handlers
private void handleRequestEvent(Map<String, Object> event) { }
private void handleDeliveryEvent(Map<String, Object> event) { }
private void handleOpenEvent(Map<String, Object> event) { }
private void handleClickEvent(Map<String, Object> event) { }
private void handleBounceEvent(Map<String, Object> event) { }
private void handleDropEvent(Map<String, Object> event) { }
private void handleSpamComplaintEvent(Map<String, Object> event) { }
private void handleUnsubscribeEvent(Map<String, Object> event) { }
}Batch Mode Support
import com.laneful.webhooks.WebhookVerifier;
import java.util.Map;
// payload: the verified raw request body
void processWebhook(String payload) {
WebhookVerifier.WebhookData webhookData = WebhookVerifier.parseWebhookPayload(payload);
if (webhookData.isBatch()) {
// Processing multiple events in batch mode
System.out.println("Processing " + webhookData.getEvents().size() + " events in batch");
} else {
// Processing single event
System.out.println("Processing single event");
}
// Process all events
for (Map<String, Object> event : webhookData.getEvents()) {
System.out.println(event.get("event") + ": " + event.get("email"));
}
}Supported Webhook Events
Delivery Events
- •
request- Email accepted and queued for delivery - •
delivery- Email delivered successfully - •
bounce- Email bounced (hard or soft) - •
drop- Email dropped (spam, invalid, etc.) - •
spam_complaint- Recipient marked email as spam
Engagement Events
- •
open- Email opened by recipient - •
click- Link clicked in email - •
unsubscribe- Recipient unsubscribed
Use version 1.2.0 or later: it supports every event type listed here, including request (earlier versions reject payloads that contain one). From 1.3.0, parseWebhookPayload also keeps events of types not listed here; 1.2.0 rejects the whole payload, every event of a batch included, if any event has such a type. Temporary delivery failures arrive as a bounce with is_hard: false rather than as a separate deferral event.
Webhook Features
Security
- • HMAC-SHA256 signature verification
- • Bare hex signatures, as Laneful sends them (a
sha256=prefix is also accepted) - • Constant-time comparison (timing attack protection)
- • Multiple header format support
Validation
- • JSON payload structure validation
- • Required field validation
- • Email format validation
- • Numeric timestamp validation
Ready to Get Started?
Start sending emails with Java in minutes. Check out the examples and integrate with your application.