What we'll build
A regular expression can tell you an address looks right. It can't tell you whether the domain exists, whether it accepts mail, or whether it's a throwaway inbox. In this guide we'll build a validateEmail() function in Kotlin that checks all of those and returns one of four statuses:
| Status | Meaning | Typical action |
|---|---|---|
valid | Well formed, and the domain accepts mail | Accept |
invalid | Bad syntax, no such domain, or no mail server | Reject and ask the user to fix it |
risky | Disposable, a likely typo, a role account, or no MX records | Your call: block, warn, or flag |
unknown | DNS failed temporarily | Accept and check again later |
You'll need Kotlin on JVM 21 or later. Steps 1 to 6 use only the JDK: DNS lookups go through its built-in JNDI DNS provider, so there's nothing to add. Step 7 uses Ktor with request validation and kotlinx.serialization:
implementation("io.ktor:ktor-server-netty:$ktor")
implementation("io.ktor:ktor-server-content-negotiation:$ktor")
implementation("io.ktor:ktor-server-request-validation:$ktor")
implementation("io.ktor:ktor-server-status-pages:$ktor")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor")Every snippet was tested with Kotlin 2.2, JVM 21 and Ktor 3.3. Using Spring Boot instead? The Java guide's @Deliverable annotation works unchanged from Kotlin. Want to see the end result first? The free email checker runs the same checks.
1. Check the syntax
Start with the check that needs no network. Instead of one huge regular expression, split the address at the last @ and check each part separately. A sealed interface for the result means when and smart casts only let you read the domain after the check passed:
package emailcheck
import java.net.IDN
// RFC 5322 "atext": the characters allowed in each dot-separated part of the local part.
private val ATOM = Regex("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+")
// A DNS label: letters, digits and hyphens, not starting or ending with a hyphen.
private val LABEL = Regex("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")
sealed interface Syntax {
data class Ok(val local: String, val domain: String, val normalized: String) : Syntax
data class Invalid(val reason: String) : Syntax
}
/** Lower-cases a domain and converts international names to punycode, or returns null. */
private fun toAsciiDomain(domain: String): String? =
runCatching { IDN.toASCII(domain.trim().removeSuffix("."), IDN.USE_STD3_ASCII_RULES).lowercase() }.getOrNull()
fun checkSyntax(input: String): Syntax {
val email = input.trim()
if (email.length > 254) return Syntax.Invalid("too_long")
val at = email.lastIndexOf('@')
if (at <= 0 || at == email.length - 1) return Syntax.Invalid("missing_at_or_part")
val local = email.substring(0, at)
if (local.toByteArray().size > 64) return Syntax.Invalid("local_part_too_long")
// split() keeps empty parts, so leading, trailing and doubled dots fail.
if (!local.split(".").all { ATOM.matches(it) }) return Syntax.Invalid("invalid_local_part")
val domain = toAsciiDomain(email.substring(at + 1)) ?: return Syntax.Invalid("invalid_domain")
val labels = domain.split(".")
if (labels.size < 2 || labels.last().all(Char::isDigit) || !labels.all { LABEL.matches(it) }) {
return Syntax.Invalid("invalid_domain")
}
return Syntax.Ok(local, domain, "${local.lowercase()}@$domain")
}Notes on the code:
IDN.toASCII()converts international domains to punycode (münchen.debecomesxn--mnchen-3ya.de), which is the form DNS needs.runCatchingturns its exception for invalid names intonull.- Kotlin's
split(".")keeps empty parts (unlike Java's), so.jane,jane.andja..neall fail with no extra rules. Regex.matches()must match the whole string, so the patterns need no^or$.- The local part limit is 64 bytes (RFC 5321), so the length is measured in UTF-8 bytes.
Only lower-case the local part when comparing addresses, to stop duplicate sign-ups. Store what the user typed, because a few mail servers still treat Jane and jane as different mailboxes.
2. Check the domain's MX records
A well-formed address is no use if its domain doesn't exist or doesn't accept mail. The domain's MX (mail exchanger) records name the servers that receive its mail. The JDK's JNDI DNS provider can look them up, and it reports a missing domain with NameNotFoundException, separately from DNS trouble, so each case gets the right status:
package emailcheck
import java.util.Hashtable
import javax.naming.Context
import javax.naming.NameNotFoundException
import javax.naming.NamingException
import javax.naming.directory.Attribute
import javax.naming.directory.InitialDirContext
data class DomainCheck(val status: String, val reason: String? = null, val mx: List<String> = emptyList())
/** "dns:" uses the system's DNS servers; tests can point it at "dns://127.0.0.1:5353". */
var dnsUrl = "dns:"
private fun context() = InitialDirContext(
Hashtable(
mapOf(
Context.INITIAL_CONTEXT_FACTORY to "com.sun.jndi.dns.DnsContextFactory",
Context.PROVIDER_URL to dnsUrl,
// A short timeout (1 s, then 2 s), so a slow DNS server can't stall a sign-up.
"com.sun.jndi.dns.timeout.initial" to "1000",
"com.sun.jndi.dns.timeout.retries" to "2",
),
),
)
/** The records of one type, or null when the domain exists but has none. */
// The trailing dot stops the resolver from trying "domain.your-search-domain" too.
private fun InitialDirContext.lookup(domain: String, type: String): Attribute? =
getAttributes("$domain.", arrayOf(type)).get(type)
fun checkDomain(domain: String): DomainCheck {
try {
val ctx = context()
val mx = try {
ctx.lookup(domain, "MX")
} catch (e: NameNotFoundException) {
return DomainCheck("invalid", "domain_not_found")
}
if (mx != null) {
// Each value looks like "10 mx.example.com.".
val records = mx.all.toList().map { it.toString().split(" ", limit = 2) }.sortedBy { it[0].toInt() }
// RFC 7505 "null MX": a single record pointing at "." means "this domain accepts no mail".
if (records.size == 1 && records[0][1] == ".") return DomainCheck("invalid", "domain_rejects_mail")
return DomainCheck("ok", mx = records.map { it[1].removeSuffix(".") })
}
// No MX records: mail servers fall back to the domain's own A/AAAA record ("implicit MX").
val hasAddress = ctx.lookup(domain, "A") != null || ctx.lookup(domain, "AAAA") != null
return if (hasAddress) DomainCheck("risky", "no_mx_records") else DomainCheck("invalid", "no_mail_server")
} catch (e: NamingException) {
// SERVFAIL, timeouts and other DNS trouble are temporary. Don't blame the user.
return DomainCheck("unknown", "dns_error")
}
}| Result | Meaning | Status |
|---|---|---|
| MX records returned | The domain accepts mail | ok |
| One MX record with an empty name | "Null MX" (RFC 7505): the domain accepts no mail | invalid |
NameNotFoundException | The domain doesn't exist | invalid |
No MX attribute in the answer | The domain exists but has no MX records, so check A/AAAA | risky or invalid |
Any other NamingException | SERVFAIL or a timeout: DNS trouble, not the user's fault | unknown |
Keep the timeout short, so a slow DNS server can't hold up a sign-up, and never treat a timeout as "invalid", or you'll turn away real users whenever DNS has a bad moment.
JNDI calls block the thread. In a Ktor route that's fine for occasional sign-ups; for heavy traffic, wrap the call in withContext(Dispatchers.IO) so it doesn't hold up a coroutine dispatcher thread.
3. Cache DNS lookups
Most of your users share a handful of domains like gmail.com and outlook.com. A server handles many requests in one process, so a shared map saves most lookups:
package emailcheck
import java.time.Instant
import java.util.concurrent.ConcurrentHashMap
private class Cached(val result: DomainCheck, val expires: Instant)
private val cache = ConcurrentHashMap<String, Cached>()
fun checkDomainCached(domain: String): DomainCheck {
cache[domain]?.takeIf { it.expires.isAfter(Instant.now()) }?.let { return it.result }
return checkDomain(domain).also { result ->
// Don't remember temporary failures.
if (result.status != "unknown") cache[domain] = Cached(result, Instant.now().plusSeconds(3600))
}
}ConcurrentHashMap is safe to use from every request at once. Don't cache failed lookups.
4. Detect disposable domains
Temporary inboxes from services like Mailinator pass every check so far: the syntax is fine and the domains have working mail servers. The only way to catch them is a list. Download the community-maintained disposable-email-domains list to your app's working directory:
curl -fsSo disposable_email_blocklist.conf https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.confpackage emailcheck
import java.io.File
// One domain per line, loaded on first use. A Set makes each lookup instant.
private val blocklist: Set<String> by lazy {
File("disposable_email_blocklist.conf").readLines().map(String::trim).filter(String::isNotEmpty).toHashSet()
}
/** Checks the domain and each parent, so "x.mailinator.com" matches "mailinator.com". */
fun isDisposable(domain: String): Boolean {
val labels = domain.split(".")
return (0 until labels.size - 1).any { i -> labels.drop(i).joinToString(".") in blocklist }
}by lazy loads the file on first use, once. Checking parent domains matters because many disposable services hand out addresses on random subdomains. New disposable domains appear every week, so download the list again from a daily job and restart.
The list also contains some typo domains, such as gmial.com and hotmial.com. Someone registered them to collect mail meant for Gmail and Hotmail users, which is why step 6 still returns a didYouMean suggestion for a disposable address. Read more about how disposable email detection works.
5. Flag role accounts and suggest typo fixes
Flag role accounts and typos too. Role accounts like info@ and support@ reach a shared inbox rather than a person, and typos like gamil.com are one of the commonest reasons a sign-up email never arrives:
package emailcheck
private val ROLE_ACCOUNTS = setOf(
"admin", "billing", "contact", "help", "hello", "info", "marketing", "no-reply",
"noreply", "office", "postmaster", "sales", "support", "team", "webmaster",
)
// Ignore "+tag" sub-addressing: "support+billing" is still "support".
fun isRoleAccount(local: String) = local.lowercase().substringBefore("+") in ROLE_ACCOUNTS
// Real providers people mistype. Include close neighbours (mail.com, ymail.com, gmx.com…)
// too, or they'd be "corrected" to the provider one letter away.
private val POPULAR_DOMAINS = listOf(
"gmail.com", "googlemail.com", "yahoo.com", "ymail.com", "yahoo.co.uk", "hotmail.com",
"hotmail.co.uk", "outlook.com", "live.com", "msn.com", "icloud.com", "me.com", "mac.com",
"aol.com", "mail.com", "gmx.com", "gmx.de", "proton.me", "protonmail.com",
)
/** Levenshtein distance: the number of single-character edits between two strings. */
fun editDistance(a: String, b: String): Int {
var prev = IntArray(b.length + 1) { it }
for (i in 1..a.length) {
val row = IntArray(b.length + 1).also { it[0] = i }
for (j in 1..b.length) {
row[j] = minOf(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + if (a[i - 1] == b[j - 1]) 0 else 1)
}
prev = row
}
return prev[b.length]
}
/** "gmial.com" → "gmail.com"; null when the domain is fine or nothing is close. */
fun suggestDomain(domain: String): String? {
if (domain in POPULAR_DOMAINS) return null
val best = POPULAR_DOMAINS.minBy { editDistance(domain, it) }
// Short domains only get one edit's leeway: two letters off "me.com" is a different domain.
return best.takeIf { editDistance(domain, it) <= if (domain.length <= 6) 1 else 2 }
}The Levenshtein distance counts two swapped letters (gmial → gmail) as two edits, which the two-edit limit for longer domains still allows. Short domains only get one edit's leeway, because a two-letter difference on me.com is a different domain.
Choose the list of domains carefully. Real providers that sit one letter apart, like mail.com and gmail.com, must both be in it, or users of one get "corrected" to the other. Even then, some genuine domains will look like typos, so show the result as a suggestion and let the user decide.
6. Put it together
Now run the checks from cheapest to most expensive and return a single verdict:
package emailcheck
import kotlinx.serialization.Serializable
/** status is "valid", "invalid", "risky" or "unknown". */
@Serializable
data class Verdict(val status: String, val reason: String, val email: String? = null, val didYouMean: String? = null)
fun validateEmail(input: String): Verdict {
val syntax = checkSyntax(input)
if (syntax !is Syntax.Ok) return Verdict("invalid", (syntax as Syntax.Invalid).reason)
val (local, domain, normalized) = syntax
val suggestion = suggestDomain(domain)
val didYouMean = suggestion?.let { "$local@$it" }
val dns = checkDomainCached(domain)
if (dns.status == "invalid" || dns.status == "unknown") return Verdict(dns.status, dns.reason!!, normalized, didYouMean)
// The domain can receive mail. Now look for risk signals, most serious first.
val reason = when {
isDisposable(domain) -> "disposable"
suggestion != null -> "possible_typo"
dns.status == "risky" -> dns.reason
isRoleAccount(local) -> "role_based"
else -> null
}
return Verdict(if (reason == null) "valid" else "risky", reason ?: "mail_server_found", normalized, didYouMean)
}It returns these results for a range of inputs:
| Input | status | reason | didYouMean |
|---|---|---|---|
jane@gmail.com | valid | mail_server_found | null |
joe@gamil.com | risky | possible_typo | joe@gmail.com |
test@mailinator.com | risky | disposable | null |
support@acme.io | risky | role_based | null |
x@no-such-domain.example | invalid | domain_not_found | null |
not-an-email | invalid | missing_at_or_part | null |
7. Use it in a Ktor route
A typical sign-up policy is to reject invalid and disposable addresses, accept everything else, and pass the typo suggestion back so the front end can ask "Did you mean …?". Ktor's RequestValidation plugin runs a check whenever a route calls receive(), and StatusPages turns a failed check into a 422:
package emailcheck
import io.ktor.http.HttpStatusCode
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import io.ktor.server.plugins.requestvalidation.RequestValidation
import io.ktor.server.plugins.requestvalidation.RequestValidationException
import io.ktor.server.plugins.requestvalidation.ValidationResult
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.post
import io.ktor.server.routing.routing
import kotlinx.serialization.Serializable
@Serializable
data class SignupRequest(val email: String)
fun Application.module() {
install(ContentNegotiation) { json() }
install(RequestValidation) {
validate<SignupRequest> { request ->
val result = validateEmail(request.email)
when {
result.status == "invalid" -> ValidationResult.Invalid("That email address can't receive mail.")
result.reason == "disposable" -> ValidationResult.Invalid("Please use a permanent email address.")
else -> ValidationResult.Valid
}
}
}
install(StatusPages) {
exception<RequestValidationException> { call, cause ->
call.respond(HttpStatusCode.UnprocessableEntity, mapOf("error" to cause.reasons.first()))
}
}
routing {
post("/signup") {
val request = call.receive<SignupRequest>() // RequestValidation runs here
val result = validateEmail(request.email) // cached: no second DNS lookup
// "unknown" means DNS had a hiccup. Accept the address and check it again later.
// users.create(result.email)
call.respond(HttpStatusCode.Created, result)
}
}
}
fun main() {
embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}The second validateEmail() call is cheap, because the domain is already cached. Adjust the policy to your product: a B2B form might also reject free providers, while a newsletter might accept role accounts.
8. Test it
The syntax check has no side effects, so it's easy to test with kotlin.test:
package emailcheck
import kotlin.test.Test
import kotlin.test.assertIs
class SyntaxTest {
@Test
fun acceptsNormalAddresses() {
for (email in listOf("jane@example.com", "jane.doe+news@example.co.uk", "user@münchen.de")) {
assertIs<Syntax.Ok>(checkSyntax(email), email)
}
}
@Test
fun rejectsMalformedAddresses() {
for (email in listOf("", "jane", "@example.com", "jane@", "a..b@example.com", "jane@example", "jane@-example.com")) {
assertIs<Syntax.Invalid>(checkSyntax(email), email)
}
}
}For the DNS checks, point JNDI at a local test DNS server with dnsUrl = "dns://127.0.0.1:5353". Then your test suite doesn't depend on the internet. That's how we tested every result on this page, including the Ktor route with testApplication.
What about checking that the mailbox exists?
You could go further with a socket: connect to the domain's mail server on port 25 and ask whether a specific mailbox exists with RCPT TO. We don't recommend doing that inside a request. Many hosting providers block outbound port 25, large providers often accept every recipient at that stage, and catch-all domains and greylisting make the answer inconclusive.
For most sign-up forms, the checks above plus a confirmation email are the best balance of accuracy and speed.
Or use an email validation API
Everything above works, but you have to maintain it: the disposable list goes stale, the typo list needs tuning, and DNS edge cases keep turning up. The validateemail.io API runs all of these checks in one request:
package emailcheck
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
data class ApiResult(val email: String, val status: String, val reason: String, val did_you_mean: String? = null)
@Serializable
private data class BatchResponse(val results: List<ApiResult>)
private const val API = "https://validateemail.io/v1"
private val http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build()
private val json = Json { ignoreUnknownKeys = true }
private fun post(path: String, body: String, timeout: Duration): String {
val request = HttpRequest.newBuilder(URI.create(API + path))
.timeout(timeout)
.header("Authorization", "Bearer ${System.getenv("VALIDATEEMAIL_KEY")}")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build()
val response = http.send(request, HttpResponse.BodyHandlers.ofString())
check(response.statusCode() == 200) { "HTTP ${response.statusCode()}" }
return response.body()
}
fun validateWithApi(email: String): ApiResult = try {
json.decodeFromString(post("/validate", json.encodeToString(mapOf("email" to email)), Duration.ofSeconds(5)))
} catch (e: Exception) {
// Never block a sign-up because the validator is slow or unreachable.
System.err.println("Email validation unavailable: $e")
ApiResult(email, "unknown", "validator_unavailable")
}
/** Validates any number of addresses, 100 per request. */
fun validateList(emails: List<String>): List<ApiResult> = emails.chunked(100).flatMap { chunk ->
json.decodeFromString<BatchResponse>(post("/validate/batch", json.encodeToString(mapOf("emails" to chunk)), Duration.ofSeconds(30))).results
}If the API is slow or unreachable, validateWithApi() returns unknown instead of throwing, so a network problem never blocks a sign-up. The response has the same status, reason and did_you_mean fields used in this guide, plus a score and the result of every individual check.
Using an AI coding assistant? Paste this prompt and it will wire up the API for you:
Add email validation to the sign-up route of this Kotlin (Ktor) app using the validateemail.io API (reference: https://validateemail.io/llms.txt).
- Call POST https://validateemail.io/v1/validate from server-side code only, with the header "Authorization: Bearer <key>" read from the VALIDATEEMAIL_KEY environment variable, and the JSON body {"email": "<address>"}. Never call it from the browser.
- Reject the address with a clear message when "status" is "invalid" or "checks.disposable" is true.
- When "did_you_mean" is set, show "Did you mean <did_you_mean>?" and let the user accept the fix.
- Use a 5-second timeout. If the API fails, times out or returns "status": "unknown", accept the address so sign-ups never break.
- Add a test that mocks the API for a valid, an invalid and a disposable address.Frequently asked questions
How do I validate an email in Kotlin?
Check the syntax first, then look up the domain's MX records to confirm it can receive mail, then check it against a disposable-domain list and for typos of popular providers. A regular expression alone only covers the first step.
How do I look up MX records in Kotlin without a library?
On the JVM, use the JDK's JNDI DNS provider: create an InitialDirContext with com.sun.jndi.dns.DnsContextFactory and call getAttributes(domain, arrayOf("MX")). A NameNotFoundException means the domain doesn't exist; other NamingExceptions are temporary DNS problems.
How do I validate request bodies in Ktor?
Install the RequestValidation plugin and register a validate<YourRequest> block. It runs when the route calls call.receive() and throws RequestValidationException on failure, which StatusPages can turn into a 400 or 422 response.
Can Kotlin check that a mailbox exists without sending an email?
You can try by opening a socket to the domain's mail server on port 25 and sending RCPT TO. In practice port 25 is often blocked, large providers accept every recipient at that stage, and catch-all domains accept anything, so the answer is often unreliable. A confirmation email is still the only definitive test.