Send OTP Emails in Actix Web / Rust (2026) with a Plain HTTP API
Build signup/login OTP in Actix Web: OsRng, HMAC-hashed codes in DashMap/Redis/SQL, rate limits, reqwest to POST /emails, and Idempotency-Key—prefer HTTP over lettre SMTP; Rovela delivers only.
Why Actix Web + OTP codes (not a magic-link SDK)
Actix Web already gives signup and login a clear shape: typed handlers, extractors, middleware for rate limits, and a server-side store (DashMap, Redis, or SQL). You do not need a Rovela Rust SDK, an "OTP product" endpoint, or middleware 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 rand::rngs::OsRng (or getrandom), stores an HMAC of it (never the digits), sets expiry and attempt limits, then POST /emails with both html and text via reqwest. 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 Actix service owns cryptography, the store entry, resend throttling, redeem logic, and the session cookie / JWT. Rovela only delivers the mail.
This article is Actix Web focused (Actix Web 4 + Tokio): handlers for "send code" and "verify code," a thin Rovela client with reqwest + Idempotency-Key, and an in-memory or Redis HMAC store so a timeout retry does not enqueue two disagreeing codes. It is not a magic-link walkthrough—for those see Next.js, NestJS, and FastAPI. Sibling OTP posts: Go (closest systems twin), Spring Boot, Express.js, Phoenix. Product choice between digits and URLs: Email verification: code vs link. Language-agnostic OTP: Sending OTP codes by email. Generic Rust transport (reqwest batches, lettre SMTP, Axum wiring, webhooks)—not OTP ownership—lives in Sending email in Rust; this post does not rehash semaphore fan-out or lettre relays.
What you own vs what Rovela sends
Your Actix service owns:
- OS CSPRNG → six digits, zero-padded (never a non-crypto PRNG for secrets)
- HMAC-SHA256 of
email + ":" + codewith a server pepper (CODE_PEPPER) via thehmac+sha2crates - 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 (
DashMap, Redis, or SQL) - Constant-time compare on redeem (
subtle::ConstantTimeEq); 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 WASM/frontend bundle, 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 (reqwest + Idempotency-Key)
# Cargo.toml (excerpt)
[dependencies]
actix-web = "4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] }
hmac = "0.12"
sha2 = "0.10"
hex = "0.4"
rand = "0.8"
subtle = "2"
dashmap = "6"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
thiserror = "1"
// src/config.rs
use std::env;
use std::time::Duration;
#[derive(Clone)]
pub struct Config {
pub api_key: String,
pub code_pepper: Vec<u8>,
pub from: String,
pub ttl: Duration,
pub resend_cooldown: Duration,
pub max_attempts: u32,
}
impl Config {
pub fn from_env() -> Self {
Self {
api_key: must_env("ROVELA_API_KEY"), // sending_access
code_pepper: must_env("CODE_PEPPER").into_bytes(),
from: env::var("OTP_FROM")
.unwrap_or_else(|_| "Acme <security@mail.acme.com>".into()),
ttl: Duration::from_secs(
env::var("OTP_TTL_MINUTES").ok().and_then(|v| v.parse().ok()).unwrap_or(10) * 60,
),
resend_cooldown: Duration::from_secs(
env::var("OTP_RESEND_COOLDOWN_SEC")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(60),
),
max_attempts: env::var("OTP_MAX_ATTEMPTS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(5),
}
}
}
fn must_env(k: &str) -> String {
env::var(k).unwrap_or_else(|_| panic!("missing env {k}"))
}
// src/rovela.rs
use reqwest::Client;
use serde_json::{json, Value};
use thiserror::Error;
#[derive(Clone)]
pub struct MailClient {
http: Client,
api_key: String,
from: String,
}
pub struct SendInput {
pub to: String,
pub subject: String,
pub html: String,
pub text: String,
pub idempotency_key: String,
}
#[derive(Debug, Error)]
pub enum MailError {
#[error("transport: {0}")]
Transport(#[from] reqwest::Error),
#[error("rovela send failed: {0} {1}")]
Status(u16, String),
}
impl MailClient {
pub fn new(api_key: String, from: String) -> Self {
Self {
http: Client::builder()
.timeout(std::time::Duration::from_secs(15))
.build()
.expect("reqwest client"),
api_key,
from,
}
}
pub async fn send(&self, in_: SendInput) -> Result<Value, MailError> {
let body = json!({
"from": self.from,
"to": in_.to,
"subject": in_.subject,
"html": in_.html,
"text": in_.text,
});
let res = self
.http
.post("https://api.rovela.dev/emails")
.header("Authorization", format!("Bearer {}", self.api_key))
.header("Idempotency-Key", in_.idempotency_key)
.header("Accept", "application/json")
.json(&body)
.send()
.await?;
let status = res.status().as_u16();
let text = res.text().await.unwrap_or_default();
if !(200..300).contains(&status) {
return Err(MailError::Status(status, text));
}
Ok(serde_json::from_str(&text).unwrap_or(json!({})))
}
}
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. Keep the key out of Actix web::Data that you accidentally serialize into responses, and never expose it through a public handler.
Hash at rest: OsRng + 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.
// src/crypto.rs
use hmac::{Hmac, Mac};
use rand::rngs::OsRng;
use rand::RngCore;
use sha2::Sha256;
use subtle::ConstantTimeEq;
type HmacSha256 = Hmac<Sha256>;
pub fn normalize_email(raw: &str) -> String {
raw.trim().to_ascii_lowercase()
}
pub fn mint_code() -> String {
// CSPRNG — ThreadRng / small PRNGs are not for secrets
let n = OsRng.next_u32() % 1_000_000;
format!("{n:06}")
}
pub fn hash_code(pepper: &[u8], email: &str, code: &str) -> String {
let mut mac = HmacSha256::new_from_slice(pepper).expect("HMAC key");
mac.update(format!("{email}:{code}").as_bytes());
hex::encode(mac.finalize().into_bytes())
}
pub fn safe_equal_hex(a: &str, b: &str) -> bool {
let (Ok(ab), Ok(bb)) = (hex::decode(a), hex::decode(b)) else {
return false;
};
if ab.len() != bb.len() {
return false;
}
ab.ct_eq(&bb).into()
}
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 DashMap<String, Record> keyed by email works for a single process. Use Redis or Postgres when you run multiple replicas.
Service: send + verify (DashMap store)
// src/service.rs
use crate::config::Config;
use crate::crypto::{hash_code, mint_code, normalize_email, safe_equal_hex};
use crate::rovela::{MailClient, SendInput};
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use std::sync::Arc;
use std::time::Duration;
#[derive(Clone)]
struct Record {
code_hash: String,
attempts: u32,
expires_at: DateTime<Utc>,
sent_at: DateTime<Utc>,
}
#[derive(Clone)]
pub struct OtpService {
cfg: Config,
mail: MailClient,
store: Arc<DashMap<String, Record>>,
}
const SAFE_SEND_MSG: &str = "If that address can receive mail, a code is on its way.";
impl OtpService {
pub fn new(cfg: Config, mail: MailClient) -> Self {
Self {
cfg,
mail,
store: Arc::new(DashMap::new()),
}
}
pub async fn send(&self, raw_email: &str) -> Result<serde_json::Value, String> {
let email = normalize_email(raw_email);
let now = Utc::now();
if let Some(rec) = self.store.get(&email) {
if now.signed_duration_since(rec.sent_at)
< chrono::Duration::from_std(self.cfg.resend_cooldown).unwrap()
{
return Ok(serde_json::json!({"ok": false, "error": "too_soon"}));
}
}
let code = mint_code();
let code_hash = hash_code(&self.cfg.code_pepper, &email, &code);
self.store.insert(
email.clone(),
Record {
code_hash: code_hash.clone(),
attempts: 0,
expires_at: now + chrono::Duration::from_std(self.cfg.ttl).unwrap(),
sent_at: now,
},
);
// Stable per logical send: hash prefix. New code ⇒ new key.
let idem = format!("otp-{}", &code_hash[..32]);
let ttl_min = self.cfg.ttl.as_secs() / 60;
self.mail
.send(SendInput {
to: email,
subject: format!("Your Acme code: {code}"),
html: format!(
"<p>Your verification code is</p>\
<p style=\"font-size:28px;font-weight:600;letter-spacing:4px\">{code}</p>\
<p>It expires in {ttl_min} minutes. If you did not ask for it, ignore this email.</p>"
),
text: format!(
"Your verification code is {code}. It expires in {ttl_min} minutes. \
If you did not ask for it, ignore this email."
),
idempotency_key: idem,
})
.await
.map_err(|e| e.to_string())?;
Ok(serde_json::json!({"ok": true, "message": SAFE_SEND_MSG}))
}
pub fn verify(&self, raw_email: &str, raw_code: &str) -> serde_json::Value {
let email = normalize_email(raw_email);
let code = raw_code.trim();
if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
return serde_json::json!({"ok": false, "error": "invalid"});
}
let Some(mut entry) = self.store.get_mut(&email) else {
return serde_json::json!({"ok": false, "error": "invalid"});
};
let now = Utc::now();
if now > entry.expires_at {
drop(entry);
self.store.remove(&email);
return serde_json::json!({"ok": false, "error": "expired"});
}
if entry.attempts >= self.cfg.max_attempts {
return serde_json::json!({"ok": false, "error": "locked"});
}
let candidate = hash_code(&self.cfg.code_pepper, &email, code);
if !safe_equal_hex(&candidate, &entry.code_hash) {
entry.attempts += 1;
return serde_json::json!({"ok": false, "error": "invalid"});
}
drop(entry);
self.store.remove(&email);
// issue session / JWT here
serde_json::json!({"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 SQL: INSERT … ON CONFLICT (email) DO UPDATE, bump attempts inside a transaction, DELETE on success.
Handlers: Actix Web + rate limits
// src/handlers.rs
use crate::service::OtpService;
use actix_web::{web, HttpResponse, Responder};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct SendBody {
email: String,
}
#[derive(Deserialize)]
pub struct VerifyBody {
email: String,
code: String,
}
pub async fn send_otp(
svc: web::Data<OtpService>,
body: web::Json<SendBody>,
) -> impl Responder {
if body.email.trim().is_empty() {
return HttpResponse::BadRequest().json(serde_json::json!({"error":"invalid_email"}));
}
match svc.send(&body.email).await {
Ok(out) if out.get("ok") == Some(&serde_json::Value::Bool(false))
&& out.get("error") == Some(&serde_json::Value::String("too_soon".into())) =>
{
HttpResponse::TooManyRequests().json(serde_json::json!({"error":"too_soon"}))
}
Ok(out) => HttpResponse::Ok().json(serde_json::json!({"message": out["message"]})),
Err(_) => HttpResponse::BadGateway().json(serde_json::json!({"error":"send_failed"})),
}
}
pub async fn verify_otp(
svc: web::Data<OtpService>,
body: web::Json<VerifyBody>,
) -> impl Responder {
let out = svc.verify(&body.email, &body.code);
if out.get("ok") == Some(&serde_json::Value::Bool(true)) {
return HttpResponse::Ok().json(serde_json::json!({"ok": true}));
}
let err = out.get("error").and_then(|v| v.as_str()).unwrap_or("invalid");
let status = if matches!(err, "locked" | "too_soon") {
actix_web::http::StatusCode::TOO_MANY_REQUESTS
} else {
actix_web::http::StatusCode::BAD_REQUEST
};
HttpResponse::build(status).json(serde_json::json!({"error": err}))
}
// src/main.rs
use actix_web::{web, App, HttpServer};
mod config;
mod crypto;
mod handlers;
mod rovela;
mod service;
use config::Config;
use handlers::{send_otp, verify_otp};
use rovela::MailClient;
use service::OtpService;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let cfg = Config::from_env();
let mail = MailClient::new(cfg.api_key.clone(), cfg.from.clone());
let svc = web::Data::new(OtpService::new(cfg, mail));
HttpServer::new(move || {
App::new()
.app_data(svc.clone())
// wrap with your IP rate-limit middleware (governor / actix-limitation / reverse proxy)
.route("/auth/otp/send", web::post().to(send_otp))
.route("/auth/otp/verify", web::post().to(verify_otp))
})
.bind(("0.0.0.0", 8080))?
.run()
.await
}
Implement per-IP limits with governor / actix-limitation, or put Cloudflare / nginx in front. Per-email cooldown inside the service and per-IP limits solve different problems—use both. Hardening checklist: Email OTP security.
Actix vs Go OTP (same contract, different crates)
| Actix Web (this post) | Go (sibling) | |
|---|---|---|
| HTTP framework | Actix handlers + extractors | net/http / chi |
| HTTP client | reqwest | stdlib net/http |
| CSPRNG | rand::rngs::OsRng | crypto/rand |
| HMAC | hmac + sha2 | crypto/hmac + crypto/sha256 |
| In-proc store | DashMap | sync.Map |
| Constant-time | subtle::ConstantTimeEq | hmac.Equal |
Both call the same POST /emails with Idempotency-Key. Neither asks Rovela to mint or verify codes.
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-actix-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 lettre / SMTP dialers for OTP in Actix
reqwest → POST /emails (this post) | lettre SMTP | |
|---|---|---|
| Transport | HTTPS 443 | 465 / 587 (25 often blocked) |
| Idempotency | Idempotency-Key header | App must dedupe |
| Feedback | Message id + webhooks | Bounce DSNs later |
| Containers / Cloud Run | 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 Rust transport patterns (including Axum wiring and lettre) live in Sending email in Rust.
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 Actix
| 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 |
| Actix 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. Never ship sending_access into a browser or WASM client either way.
Checklist before you ship
OsRng/getrandom+ HMAC pepper; never store raw codes; never use a weak PRNG 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—never in frontend / WASM.Idempotency-Keystable per logical send; new code → new key.- Uniform messaging if you hide account existence.
- Prefer HTTP API over 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.
- Systems twin: Go OTP · other OTP stacks: Spring Boot · Express · Phoenix.
- Rust transport only (not OTP): Sending email in Rust.
- Magic-link siblings: Next.js · NestJS · FastAPI.
Bottom line: put signup/login OTP in Actix handlers that mint OsRng codes, HMAC them at rest (DashMap, Redis, or SQL), rate-limit send/verify, and call one reqwest POST to Rovela with an Idempotency-Key—prefer that over lettre SMTP dialers, and never pretend the email API is your auth server.