Quick Start: Java Email Webhook
JsonHook delivers every inbound email as a JSON POST request to your webhook endpoint. Setting up a Java handler takes less than 5 minutes. Start by initializing your project:
# Spring Boot: add spring-boot-starter-web to pom.xml or build.gradle
Then create your webhook endpoint. The following example shows the minimal code needed to receive and acknowledge a JsonHook delivery:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
@RestController
public class WebhookController {
private final ObjectMapper mapper = new ObjectMapper();
@PostMapping("/webhook")
public ResponseEntity webhook(HttpServletRequest request) throws Exception {
byte[] body = request.getInputStream().readAllBytes();
JsonNode payload = mapper.readTree(body);
String from = payload.path("email").path("from").asText();
String subject = payload.path("email").path("subject").asText();
System.out.println("Email from: " + from + " | Subject: " + subject);
return ResponseEntity.ok("ok");
}
}
Point your JsonHook address webhook URL to this endpoint and you will start receiving parsed emails as JSON within seconds of the email arriving.
Full Java Implementation
The quick start example above is enough to get started, but a production implementation should include signature verification, structured error handling, and proper HTTP response codes. The complete example below demonstrates all of these patterns together.
This implementation verifies the X-JsonHook-Signature header to confirm the request genuinely came from JsonHook, parses the full email payload, and returns the appropriate HTTP status codes to trigger or suppress retries.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
@RestController
public class WebhookController {
private static final String SECRET = System.getenv("JSONHOOK_WEBHOOK_SECRET");
private final ObjectMapper mapper = new ObjectMapper();
private boolean verifySignature(byte[] body, String sigHeader) throws Exception {
if (sigHeader == null || sigHeader.isEmpty()) return false;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] computed = mac.doFinal(body);
String computedHex = HexFormat.of().formatHex(computed);
// MessageDigest.isEqual is constant-time
return MessageDigest.isEqual(
computedHex.getBytes(StandardCharsets.UTF_8),
sigHeader.getBytes(StandardCharsets.UTF_8)
);
}
@PostMapping("/webhook")
public ResponseEntity webhook(HttpServletRequest request) throws Exception {
byte[] body = request.getInputStream().readAllBytes();
String signature = request.getHeader("X-JsonHook-Signature");
if (!verifySignature(body, signature)) {
return ResponseEntity.status(401).body("Unauthorized");
}
JsonNode payload = mapper.readTree(body);
JsonNode email = payload.path("email");
String event = payload.path("event").asText();
String timestamp = payload.path("timestamp").asText();
String address = payload.path("address").asText();
String from = email.path("from").asText();
String subject = email.path("subject").asText();
String textBody = email.path("textBody").asText();
System.out.printf("[%s] Email at %s from %s%n", timestamp, address, from);
System.out.println("Subject: " + subject);
JsonNode attachments = email.path("attachments");
for (JsonNode att : attachments) {
System.out.printf("Attachment: %s (%s, %d bytes)%n",
att.path("filename").asText(),
att.path("contentType").asText(),
att.path("size").asInt());
}
return ResponseEntity.ok("ok");
}
}
The webhook handler returns 200 immediately after queuing the email for processing. Avoid doing expensive work (database writes, API calls) synchronously inside the handler — process the payload in a background job to stay within JsonHook's 10-second response timeout.
Build Your Java Email Integration
Free API key — start receiving webhooks in 5 minutes.
Get Free API KeyParsing the Webhook Payload
Every JsonHook delivery is an HTTP POST with Content-Type: application/json. The payload follows a consistent schema regardless of the originating email client or provider:
ObjectMapper mapper = new ObjectMapper();
JsonNode payload = mapper.readTree(body); // body is byte[]
String event = payload.path("event").asText(); // "email.received"
String timestamp = payload.path("timestamp").asText(); // ISO 8601 string
String address = payload.path("address").asText(); // "[email protected]"
JsonNode email = payload.path("email");
String from = email.path("from").asText();
String subject = email.path("subject").asText();
String textBody = email.path("textBody").asText();
String htmlBody = email.path("htmlBody").asText();
// Iterate attachments
for (JsonNode att : email.path("attachments")) {
String filename = att.path("filename").asText();
String contentType = att.path("contentType").asText();
int size = att.path("size").asInt();
}
Key fields in the payload:
- event — Always
"email.received"for inbound email events - timestamp — ISO 8601 timestamp of when JsonHook received the email
- address — The JsonHook inbound address that received the email (e.g.,
[email protected]) - email.from — Sender address string, e.g.,
"Alice <[email protected]>" - email.to — Array of recipient address strings
- email.subject — Email subject line
- email.textBody — Plain text body of the email (may be empty if HTML-only)
- email.htmlBody — HTML body of the email (may be empty if plain-text-only)
- email.attachments — Array of attachment objects, each with
filename,contentType,size, andcontentId
Verifying Webhook Signatures
JsonHook signs every webhook delivery using HMAC-SHA256. The signature is included in the X-JsonHook-Signature request header as a hex digest. To verify it, compute the HMAC-SHA256 of the raw request body using your address's webhook secret and compare it to the header value.
Your webhook secret is returned when you create an inbound address via the API (POST /api/addresses). Store it as an environment variable — never hard-code it.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
public static boolean verifyJsonHookSignature(byte[] body, String sigHeader, String secret)
throws Exception {
if (sigHeader == null || secret == null) return false;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] computed = mac.doFinal(body);
String computedHex = HexFormat.of().formatHex(computed);
// MessageDigest.isEqual performs a constant-time comparison
return MessageDigest.isEqual(
computedHex.getBytes(StandardCharsets.UTF_8),
sigHeader.getBytes(StandardCharsets.UTF_8)
);
}
Always verify the signature before processing the payload. Return 401 for invalid signatures so that legitimate retries from JsonHook (which always include a valid signature) are distinguishable from spoofed requests.
Error Handling Best Practices
Reliable webhook handling requires careful attention to error responses. JsonHook uses your HTTP response code to decide whether to retry a delivery:
- Return 200 quickly: Acknowledge receipt immediately and process asynchronously. JsonHook will retry any non-2xx response.
- Return 400 for bad requests: If the payload fails your own validation (not signature — use 401 for that), return 400 to prevent retries of malformed deliveries.
- Return 500 to trigger retries: If your downstream system is temporarily unavailable, returning 500 causes JsonHook to retry with exponential backoff (up to 5 attempts over ~1 hour).
- Never return 200 before verifying the signature: Doing so silently accepts spoofed requests.
Java ecosystem tips:
- Read the raw input stream with
request.getInputStream().readAllBytes()before Spring processes the body — Spring may buffer it, but always verify using the raw bytes - Use
MessageDigest.isEqual()for constant-time byte array comparison instead ofArrays.equals()or string.equals() - Use
@Asyncor submit a task to anExecutorServiceto process email payload after returning the 200 response - Configure
spring.mvc.async.request-timeoutappropriately and ensure your@PostMappinghandler returns quickly by delegating heavy processing
Java Ecosystem Tips
The Java ecosystem offers several libraries and patterns that pair well with JsonHook webhook handling. Here are general recommendations:
- Use a well-maintained HTTP server library appropriate for your use case — the examples in this guide use the most common choice, but any library that gives you raw body access works.
- Store your webhook secret in an environment variable and load it via your language's standard env access pattern — never commit secrets to version control.
- Use your language's standard HMAC library rather than a third-party package — all languages featured in this guide have HMAC-SHA256 in their standard library.
- Consider a structured logging library to capture the
address,event, andtimestampfields from every webhook delivery for observability. - Test your handler locally using a tunneling tool like ngrok or a local webhook testing service before pointing your JsonHook address at a production URL.