The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications.
The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.
This Java 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.
If you are getting above exception in your Eclipse IDE then you may need to add below Maven JavaMail API dependency.
<dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.6.2</version> </dependency>
Another must read:
package com.crunchify.tutorials; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; /** * @author Crunchify.com * */ public class CrunchifyValidateEmail { public static void main(String[] args) { CrunchifyValidateEmail crunchifyCheck = new CrunchifyValidateEmail(); // Specify Boolean Flag boolean isValid = false; String email = "hello@crunchify.com"; isValid = crunchifyCheck.crunchifyEmailValidator(email); crunchifyCheck.myLogger(email, isValid); email = "hello.crunchify"; isValid = crunchifyCheck.crunchifyEmailValidator(email); crunchifyCheck.myLogger(email, isValid); email = "hello.crunchify@"; isValid = crunchifyCheck.crunchifyEmailValidator(email); crunchifyCheck.myLogger(email, isValid); } private boolean crunchifyEmailValidator(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) { System.out.println("You are in catch block -- Exception Occurred for: " + email); } return isValid; } private void myLogger(String email, boolean valid) { System.out.println(email + " is " + (valid ? "a" : "not a") + " valid email address\n"); } }
Output:
hello@crunchify.com is a valid email address You are in catch block -- Exception Occurred for: hello.crunchify hello.crunchify is not a valid email address You are in catch block -- Exception Occurred for: hello.crunchify@ hello.crunchify@ is not a valid email address
If may be interested in List of all Spring MVC, JSON Examples.