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 using new InternetAddress(email), where email 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button