Send OTP Emails in Spring Boot (2026) with a Plain HTTP API
Build signup/login OTP in Spring Boot: SecureRandom, HMAC-hashed codes in ConcurrentHashMap/Redis/JPA, rate limits, RestClient or WebClient to POST /emails, and Idempotency-Key—prefer HTTP over Jakarta Mail; Rovela delivers only.
Why Spring Boot + OTP codes (not a JavaMail SDK)
Spring Boot already gives signup and login a familiar shape: @RestController endpoints, filter/interceptor rate limits, and a server-side store (ConcurrentHashMap, Redis via Spring Data, or JPA). You do not need a Rovela Java SDK, an “OTP product” endpoint, or a starter that pretends the email API is an identity provider.
What you need is the recipe in Email verification codes: your app mints a six-digit code with SecureRandom, stores an HMAC of it (never the digits), sets expiry and attempt limits, then POST /emails with both html and text via Spring’s RestClient (Boot 3.2+) or WebClient. Rovela queues, DKIM-signs, retries, and records events. It does not generate codes, check them, or create sessions.
Rovela does not provide an OTP feature. Your Spring service owns cryptography, the store entry, resend throttling, redeem logic, and the session cookie / JWT. Rovela only delivers the mail.
This article is Spring Boot focused (3.x / Java 17+): controllers for “send code” and “verify code,” a thin Rovela client bean, an in-memory or Redis HMAC store, and an Idempotency-Key so a timeout retry does not enqueue two disagreeing codes. It is not a magic-link walkthrough—for those see Next.js, NestJS, Rails, and FastAPI. Sibling OTP posts: Express.js, Django, Laravel, Go. Product choice between digits and URLs: Email verification: code vs link. Language-agnostic OTP: Sending OTP codes by email. Generic Java / Kotlin transport (not OTP): Sending email in Java and Sending email in Kotlin—this post does not rehash Jakarta Mail SMTP dialers, MIME builders, or one-off “hello world” sends.
What you own vs what Rovela sends
Your Spring Boot app owns:
SecureRandom→ six digits, zero-padded (neverMath.random()/Random)- HMAC-SHA256 of
email + ":" + codewith a server pepper (CODE_PEPPER) viaMac.getInstance("HmacSHA256") - Expiry (docs example: ~10 minutes), attempt counter, and “one send per minute” resend gate
- Upsert by normalized email so a new send invalidates the previous code (
ConcurrentHashMap, Redis, or JPA) - Constant-time compare on redeem (
MessageDigest.isEqual); delete / invalidate on success - Identical public responses whether or not you want to reveal account existence (product choice)
- Rate limits on
/auth/otp/sendand/auth/otp/verify
Rovela owns:
POST https://api.rovela.dev/emailswithAuthorization: Bearer+ asending_accesskey (ROVELA_API_KEYin env—never commit it, never put it in a public config, never log it)- Queueing, signing, retries, bounce/complaint handling
A 200 from the send endpoint means accepted and queued, not “in the inbox.”
Env and a tiny Rovela client (RestClient)
# application.properties (or env / secrets manager)
rovela.api-key=${ROVELA_API_KEY}
rovela.from=Acme <security@mail.acme.com>
otp.code-pepper=${CODE_PEPPER}
otp.ttl-minutes=10
otp.resend-cooldown-seconds=60
otp.max-attempts=5
// RovelaProperties.java
package com.example.otp;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "rovela")
public record RovelaProperties(String apiKey, String from) {}
// OtpProperties.java
package com.example.otp;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "otp")
public record OtpProperties(
String codePepper,
int ttlMinutes,
int resendCooldownSeconds,
int maxAttempts
) {}
// RovelaMailClient.java
package com.example.otp;
import java.util.Map;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
@Component
public class RovelaMailClient {
private final RestClient http;
private final RovelaProperties props;
public RovelaMailClient(RestClient.Builder builder, RovelaProperties props) {
this.props = props;
this.http = builder.baseUrl("https://api.rovela.dev").build();
}
public Map<?, ?> send(String to, String subject, String html, String text, String idempotencyKey) {
return http.post()
.uri("/emails")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + props.apiKey())
.header("Idempotency-Key", idempotencyKey)
.header("Accept", "application/json")
.body(Map.of(
"from", props.from(),
"to", to,
"subject", subject,
"html", html,
"text", text
))
.retrieve()
.body(Map.class);
}
}
// WebClient alternative (reactive stack)
// webClient.post().uri("https://api.rovela.dev/emails")
// .header("Authorization", "Bearer " + apiKey)
// .header("Idempotency-Key", key)
// .bodyValue(payload)
// .retrieve()
// .bodyToMono(Map.class);
Wire ROVELA_API_KEY and CODE_PEPPER like any other server secret (Authentication, Quick Start). A sending_access key is enough—and preferred—for production OTP senders. Enable the properties with @EnableConfigurationProperties({RovelaProperties.class, OtpProperties.class}).
Hash at rest: SecureRandom + HMAC, not bare SHA-256
Six digits are only a million possibilities. A leaked table of bare SHA-256 hashes is reversed in well under a second. Follow the docs: HMAC with a pepper that never leaves the server.
// OtpCrypto.java
package com.example.otp;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public final class OtpCrypto {
private static final SecureRandom RNG = new SecureRandom();
private OtpCrypto() {}
public static String normalizeEmail(String raw) {
return raw == null ? "" : raw.trim().toLowerCase();
}
public static String mintCode() {
// CSPRNG — Math.random() / java.util.Random are not for secrets
int n = RNG.nextInt(1_000_000);
return String.format("%06d", n);
}
public static String hashCode(String pepper, String email, String code) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(pepper.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] out = mac.doFinal((email + ":" + code).getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(out);
} catch (Exception e) {
throw new IllegalStateException("HMAC failed", e);
}
}
public static boolean safeEqualHex(String a, String b) {
byte[] ab = HexFormat.of().parseHex(a);
byte[] bb = HexFormat.of().parseHex(b);
return MessageDigest.isEqual(ab, bb);
}
}
Suggested row shape (one active code per email), matching the verification-code example:
CREATE TABLE verification_codes (
email TEXT PRIMARY KEY,
code_hash TEXT NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
attempts INT NOT NULL DEFAULT 0,
sent_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
In-memory sketch for demos: a ConcurrentHashMap keyed by email works for a single JVM. Use Redis (StringRedisTemplate) or Postgres when you run multiple replicas.
Service: send + verify (ConcurrentHashMap store)
// OtpRecord.java
package com.example.otp;
import java.time.Instant;
record OtpRecord(String codeHash, int attempts, Instant expiresAt, Instant sentAt) {
OtpRecord withAttempts(int n) {
return new OtpRecord(codeHash, n, expiresAt, sentAt);
}
}
// OtpService.java
package com.example.otp;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Service;
@Service
public class OtpService {
private static final String SAFE_SEND_MSG =
"If that address can receive mail, a code is on its way.";
private final OtpProperties cfg;
private final RovelaMailClient mail;
private final ConcurrentHashMap<String, OtpRecord> store = new ConcurrentHashMap<>();
public OtpService(OtpProperties cfg, RovelaMailClient mail) {
this.cfg = cfg;
this.mail = mail;
}
public Map<String, Object> send(String rawEmail) {
String email = OtpCrypto.normalizeEmail(rawEmail);
Instant now = Instant.now();
OtpRecord existing = store.get(email);
if (existing != null
&& now.isBefore(existing.sentAt().plusSeconds(cfg.resendCooldownSeconds()))) {
return Map.of("ok", false, "error", "too_soon");
}
String code = OtpCrypto.mintCode();
String codeHash = OtpCrypto.hashCode(cfg.codePepper(), email, code);
store.put(
email,
new OtpRecord(
codeHash,
0,
now.plusSeconds(cfg.ttlMinutes() * 60L),
now));
// Stable per logical send: hash prefix. New code ⇒ new key.
String idem = "otp-" + codeHash.substring(0, 32);
int ttlMin = cfg.ttlMinutes();
String html =
"<p>Your verification code is</p>"
+ "<p style=\"font-size:28px;font-weight:600;letter-spacing:4px\">"
+ code
+ "</p>"
+ "<p>It expires in "
+ ttlMin
+ " minutes. If you did not ask for it, ignore this email.</p>";
String text =
"Your verification code is "
+ code
+ ". It expires in "
+ ttlMin
+ " minutes. If you did not ask for it, ignore this email.";
mail.send(email, "Your Acme code: " + code, html, text, idem);
return Map.of("ok", true, "message", SAFE_SEND_MSG);
}
public Map<String, Object> verify(String rawEmail, String rawCode) {
String email = OtpCrypto.normalizeEmail(rawEmail);
String code = rawCode == null ? "" : rawCode.trim();
if (code.length() != 6 || !code.chars().allMatch(Character::isDigit)) {
return Map.of("ok", false, "error", "invalid");
}
OtpRecord rec = store.get(email);
if (rec == null) {
return Map.of("ok", false, "error", "invalid");
}
Instant now = Instant.now();
if (now.isAfter(rec.expiresAt())) {
store.remove(email);
return Map.of("ok", false, "error", "expired");
}
if (rec.attempts() >= cfg.maxAttempts()) {
return Map.of("ok", false, "error", "locked");
}
String actual = OtpCrypto.hashCode(cfg.codePepper(), email, code);
if (!OtpCrypto.safeEqualHex(actual, rec.codeHash())) {
store.put(email, rec.withAttempts(rec.attempts() + 1));
return Map.of("ok", false, "error", "invalid");
}
store.remove(email);
// issue session / JWT here
return Map.of("ok", true);
}
}
Putting the code in the subject helps lock-screen previews—fine for many products; skip it on highly shared screens (verification-code docs). Always send both html and text with the digits in the text part (POST /emails).
For Redis: SET otp:{email} {json} with TTL = expiry, plus SET otp:cooldown:{email} 1 EX 60. For JPA/SQL: upsert on email, bump attempts inside a transaction, DELETE on success.
Controllers + rate limits
// OtpController.java
package com.example.otp;
import java.util.Map;
import org.springframework.http.HttpStatus;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/auth/otp")
public class OtpController {
private final OtpService svc;
public OtpController(OtpService svc) {
this.svc = svc;
}
public record SendBody(String email) {}
public record VerifyBody(String email, String code) {}
@PostMapping("/send")
public ResponseEntity<?> send(@RequestBody SendBody body) {
if (body.email() == null || body.email().isBlank()) {
return ResponseEntity.badRequest().body(Map.of("error", "invalid_email"));
}
try {
Map<String, Object> out = svc.send(body.email());
if (Boolean.FALSE.equals(out.get("ok"))) {
if ("too_soon".equals(out.get("error"))) {
return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS)
.body(Map.of("error", "too_soon"));
}
}
return ResponseEntity.ok(Map.of("message", out.get("message")));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
.body(Map.of("error", "send_failed"));
}
}
@PostMapping("/verify")
public ResponseEntity<?> verify(@RequestBody VerifyBody body) {
Map<String, Object> out = svc.verify(body.email(), body.code());
if (Boolean.FALSE.equals(out.get("ok"))) {
HttpStatus status =
"locked".equals(out.get("error")) || "too_soon".equals(out.get("error"))
? HttpStatus.TOO_MANY_REQUESTS
: HttpStatus.BAD_REQUEST;
return ResponseEntity.status(status).body(Map.of("error", out.get("error")));
}
return ResponseEntity.ok(Map.of("ok", true));
}
}
Add a Bucket4j / Resilience4j filter (or put Cloudflare / nginx in front) for per-IP limits on /auth/otp/**. Per-email cooldown inside the service and per-IP limits solve different problems—use both. Hardening checklist: Email OTP security.
Idempotency-Key: retries without double codes
Workers, reverse proxies, and AI agents retry. Without Idempotency-Key, a timeout can deliver two codes that disagree in the user’s inbox.
- Header ≤ 256 characters; Rovela remembers it for 24 hours and returns the original response on replay (API: emails).
- Derive the key from the code hash (
otp-+ first 32 hex chars) so one logical mint maps to one queued message. - A deliberate resend after cooldown mints a new code → new hash → new key. Do not reuse the old key for a new code.
curl -X POST https://api.rovela.dev/emails \
-H "Authorization: Bearer $ROVELA_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: otp-smoke-spring-2026-11-05" \
-d '{
"from": "Acme <security@mail.acme.com>",
"to": "you@example.com",
"subject": "Your Acme code: 482913",
"html": "<p>Your verification code is <b>482913</b>. Expires in 10 minutes.</p>",
"text": "Your verification code is 482913. Expires in 10 minutes."
}'
Why not Jakarta Mail SMTP for OTP in Spring
RestClient / WebClient → POST /emails (this post) | Jakarta Mail / Spring JavaMailSender | |
|---|---|---|
| Transport | HTTPS 443 | 465 / 587 (25 often blocked) |
| Idempotency | Idempotency-Key header | App must dedupe |
| Feedback | Message id + webhooks | Bounce DSNs later |
| Containers / K8s | Port 443 always open | SMTP often restricted |
| OTP fit | JSON html + text | Hand-built MIME |
Use SMTP when you already depend on it. For new signup/login digits, call the HTTP API. Broader Java transport patterns live in Sending email in Java.
Deliverability notes for auth digits (not magic URLs)
OTP mail is short and sensitive. Prefer a verified subdomain such as security@mail.example.com, aligned SPF/DKIM/DMARC, and low HTML chrome. Codes in the body (and often the subject) do not need clickable links—so click-tracking rewrites matter less than for magic links—but open/click tracking settings still belong on a domain you control.
If codes land in spam, use the checklist in Why OTP and magic-link emails go to spam. For whether your product should use digits at all versus a confirmation URL, see code vs link.
OTP codes vs magic links in Spring Boot
| Six-digit OTP (this post) | Magic link | |
|---|---|---|
| User action | Type digits | Click URL |
| Secret entropy | Low → HMAC + pepper required | High URL token → SHA-256 of token is usually enough |
| Docs shape | Verification codes | Password reset / link pattern |
| Spring surface | POST /auth/otp/send + POST /auth/otp/verify | POST /auth/magic/request + GET /auth/magic?token= |
| Click tracking | Optional concern | Prefer off on the security sending domain |
Both call the same POST /emails. Keep separate stores—do not reuse an OTP record as a magic-link token.
Checklist before you ship
SecureRandom+ HMAC pepper; never store raw codes; never useMath.random()for OTP.- ~10 minute TTL, attempt cap, per-email resend cooldown, per-IP rate limit.
- Upsert / overwrite invalidates the previous code; verify deletes on success.
htmlandtext; optional subject code for previews.ROVELA_API_KEY(sending_access) only on the server.Idempotency-Keystable per logical send; new code → new key.- Uniform messaging if you hide account existence.
- Prefer HTTP API over Jakarta Mail SMTP for OTP; verified from-domain; spam checklist if inbox placement slips.
Related reading
- Docs: Email verification codes · POST /emails · Quick Start · Authentication.
- Product-agnostic OTP: Sending OTP codes by email · Email OTP security.
- UX choice: Email verification: code vs link.
- Deliverability: Why OTP and magic-link emails go to spam.
- Framework siblings: Express OTP · Django OTP · Laravel OTP · Go OTP · magic-link Next.js / NestJS / Rails / FastAPI.
- Java / Kotlin transport only: Sending email in Java · Sending email in Kotlin.
Bottom line: put signup/login OTP in Spring Boot controllers that mint SecureRandom codes, HMAC them at rest (ConcurrentHashMap, Redis, or JPA), rate-limit send/verify, and call one RestClient/WebClient POST to Rovela with an Idempotency-Key—prefer that over Jakarta Mail SMTP, and never pretend the email API is your auth server.