How do I validate email address using Java Mail API?

This code snippet shows you how to validate an email address using the javax.mail.internet.InternetAddress class. The validate() method throws a javax.mail.internet.AddressException when the email address passed to the constructor is not a valid email address.

Here is the complete code snippet:

package org.kodejava.example.mail;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

public class ValidateEmail {
    public static void main(String[] args) {
        ValidateEmail demo = new ValidateEmail();

        String email = "[email protected]";
        boolean isValid = demo.validateEmail(email);
        demo.printStatus(email, isValid);

        email = "kodejava.gmail";
        isValid = demo.validateEmail(email);
        demo.printStatus(email, isValid);
    }

    private boolean validateEmail(String email) {
        boolean isValid = false;
        try {
            //
            // Create InternetAddress object and validated the supplied
            // address which is this case is an 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");
    }
}

When running the program you will get the following message printed on the screen. For simplicity I’ve remove the complete error stack trace.

[email protected] is a valid email address
kodejava.gmail is not a valid email address
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply