How to validate email addresses in Java
Fake email addresses are a real pain to deal with, especially where bulk communication is concerned. They can also throw a wrench in service registration. Let’s look at how to instantly defeat this irritation without wasting more than 5 minutes of your time.
First we need to add references to Maven POM so that Jitpack can compile the library that we will need.
Repository reference:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Depenedency reference:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.75</version>
</dependency>
</dependencies>
With that out of the way, we just need to call emailFullValidation using the following code:
// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.EmailApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");EmailApi apiInstance = new EmailApi();String email = "email_example"; // String | Email address to validate, e.g. \"support@cloudmersive.com\". The input is a string so be sure to enclose it in double-quotes.try {FullEmailValidationResponse result = apiInstance.emailFullValidation(email);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling EmailApi#emailFullValidation");e.printStackTrace();}
The API will not only check basic syntax, but also identify the mail server and validate the email address directly. This is a significant improvement over basic syntax validation, which is very easy to fool. If you would prefer to use an alternative method that is faster but less accurate, you can also call emailAddressGetServers.