How to validate email addresses in Java

Check if an email address is correct and really exists using standard java

You can easily test if an email address is formatted correctly with a regex, like in the example bellow. But it will miss many important cases, like if the email address is well formed but the emails will bounce, because the account never existed or has recently been disabled.

email_pattern.java
if ("foo@bar.com".matches("[^@]+@[^@]+\\.[^@]+")) {
// email matches pattern
} else {
// email doesnt match pattern
}

Real email API validation

To do full email validation inspecting the mail server you can use isitarealemail.com and make a requests call to check it. This will do the check via the real email service which will make sure the requests are not blocked.

email_validate.java
String email = ???;
String apiKey = ???;
HttpClient client = HttpClient.newBuilder().build();
String jsonResult = client.send(
HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://isitarealemail.com/api/email/validate?email="+email))
.setHeader("Authorization", "Bearer " + apiKey)
.build(),
HttpResponse.BodyHandlers.ofString(),
).body()
String status = new JSONObject(jsonResult).getString("status");
if (status == "valid") {
// the email is valid
} else {
// the email is invalid
}

Be sure to signup and get your own API key.

Get started with real email validations today.