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.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.example";
        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.

[email protected] is a valid email address
kodejava.example is not a valid email address
javax.mail.internet.AddressException: Missing final '@domain' in string ``kodejava.example''
    at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:1279)
    at javax.mail.internet.InternetAddress.validate(InternetAddress.java:1154)
    at org.kodejava.mail.ValidateEmail.validateEmail(ValidateEmail.java:25)
    at org.kodejava.mail.ValidateEmail.main(ValidateEmail.java:15)

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
</dependencies>

Maven Central Maven Central

Wayan

Leave a Reply

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