mail
Validate email address with Java Mail API
In this example we are going to see how to validate email addresses using Java Mail API. The mail API provides the programmer an easy to use suite in order to handle mail management inside his application. You can use this example when you want to perform input validation on your parameters before using them.
In order to validate email address with Java Mail API you should:
- Create
InternetAddress
object usingnew InternetAddress(email)
, whereemail
is the email address you want to validate. - Validated the email address using
internetAddress.validate()
.
Here is the code:
package com.javacodegeeks.snippets.enterprise; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; public class ValidateEmailExample { public static void main(String[] args) { ValidateEmailExample example = new ValidateEmailExample(); String email = "email@javacodegeeks.com"; boolean isValid = example.validateEmail(email); example.printStatus(email, isValid); email = "email.javacodegeks"; isValid = demo.validateEmail(email); example.printStatus(email, isValid); } private boolean validateEmail(String email) { boolean isValid = false; try { //Create InternetAddress object and validated the email address. InternetAddress internetAddress = new InternetAddress(email); internetAddress.validate(); isValid = true; } catch (AddressException e) { e.printStackTrace(); } return isValid; } private void printStatus(String email, boolean valid) { System.out.println(email + " is " + (valid ? "a" : "not a") + " valid email address"); } }
Output:
email@javacodegeeks.com is a valid email address
email.javacodegeks is not a valid email address
This is an example on how to validate email address with Java Mail API.