A modern and lightweight library for working with email addresses in Java
A modern and lightweight library for working with email addresses in Java
A modern, fast, zero-dependency library for parsing, validating, and working with email addresses in Java.
Built for Java 8 and up.
Why JMail? • Installation • Performance • Usage • IP Validation • Contributing
JMail was built mainly because I wanted to tackle the complex problem of email address validation without using Regex. Along the way, JMail became a much better choice than other Java email validation libraries (such as Apache Commons Validator, Jakarta Mail Validation, or Google dot-parse) for the following reasons:
JMail is more correct than other libraries. For example, both
Apache Commons and Jakarta Mail consider first@[email protected] as a valid
email address! It clearly is not, as it has two @ characters. JMail correctly
considers this address invalid. No other library does better than 78% correct (JMail is 100%)! You can
see a full comparison of correctness and try it out for yourself online.
JMail is faster than other libraries by, on average, at least 2x, thanks in part to lack of regex. See the performance section for more details.
JMail has zero dependencies and is very lightweight.
JMail is customizable and feature-rich. You can provide custom validation rules, directly access different parts of the email addresses, and transform addresses into a wide variety of canonical formats.
JMail is modern. It is built for Java 8+, and provides many useful methods, data accessors, and canonical address formats.
Click here for a full report of the differences in correctness and speed between JMail and other libraries.
While JMail is more correct than other libraries, I cannot guarantee that it is 100% correct. Email RFCs are long and complex, and I have likely missed some specific details. Please open an issue if you find an incorrect validation result for a specific email (or even better, a pull request with a fix). I also highly recommend that you send verification emails to user-provided email addresses. This is the only way to ensure that the email address exists and that the recipient wants that email address to be used.
Add this library as a dependency in your pom.xml:
com.sanctionco.jmail
jmail
2.2.2
Or in your build.gradle:
implementation 'com.sanctionco.jmail:jmail:2.2.2'Average validation time in nanoseconds per operation (ns/op), measured with JMH.
JMail can take slightly longer (tens of nanoseconds) than Jakarta for some valid address because of the
comprehensivity of its checks. Note that Jakarta Mail has the worst correctness result of all
competing libraries (61.5% correct). The main loop in JMail ensures full RFC correctness and so requires more
and branches in the logic than any implementation that reduces the RFC set they validate against. Even so,
invalid addresses complete much quicker than Jakarta Mail. Despite all the extra logic, JMail has fantastic performance
numbers across the board, beating all other implementations, and doesn't give up anything in correctness. No matter what
address you give JMail, time only increases based on the length or complexity of the address, making it truly an O(n) solution.
Note that some implementations throw exceptions on invalid addresses, which does impact their performance results since exception handling is expensive in Java. This is still an accurate representation since these implementations do not provide an API to validate without exceptions.
This consistent performance, combined with much better correctness, a richer API set, and more out-of-the-box customization and canonicalization options, makes JMail the best choice for email address parsing and validation.
| Email address | JMail | Jakarta Mail | Google dot-parse | Apache Commons | email-rfc2822 |
|---|---|---|---|---|---|
[email protected] |
98 | 71 | 167 | 678 | 2034 |
[email protected] |
258 | 175 | 297 | 1573 | 5129 |
user@münchen.de |
647 | 63 | 663 | 1331 | 2229 |
[email protected] |
168 | 86 | 215 | 776 | 1821 |
first@[email protected] (Invalid) |
35 | 815 | 1393 | 411 | 2867 |
valid.local@exam_ple.com (Invalid) |
59 | 835 | 1421 | 881 | 3384 |
"john doe"(a comment)@example.com (Invalid) |
348 | 501 | 1508 | 719 | 8433 |
JMail address list parsing (parsing addresses from a comma-separated String) is also faster than the competition.
| Address list | JMail | Google dot-parse |
|---|---|---|
3 valid addresses [email protected],[email protected],[email protected] |
450 | 786 |
2 addresses, one with display name Joe A Smith ,[email protected] |
512 | 545 |
3 addresses, 2 of them invalid e_[email protected],[email protected].,[email protected] |
389 | 1706 |
To perform standard, RFC-compliant email validation, you can use the static methods
available in JMail. For example, to test validation:
String email = "[email protected]";
if (JMail.isValid(email)) {
// Work with your email string
}Or to enforce validation, throwing an InvalidEmailException on failure:
String email = "[email protected]";
try {
JMail.enforceValid(email);
// Work with your email string
} catch (InvalidEmailException _) {
// Handle invalid email
}You can also retrieve the reason for validation failure with the validate method:
String email = "[email protected]"
EmailValidationResult result = JMail.validate(email);
if (result.isSuccess()) {
// Use the email address
} else {
FailureReason reason = result.getFailureReason();
logger.error("Validating email address failed with reason: " + reason);
}JMail also provides an EmailValidator class that allows for much more
customization of what constitutes a valid email address. You can require
additional common validation rules,
or supply your own. For example:
…Email ObjectJMail also includes an Email object that makes working with
email addresses easier. The Email object has the following properties:
| Property getter | Description | Example using test(hello)@(world)example.one.com |
|---|---|---|
| localPart() | The local-part of the email address | test(hello) |
| localPartWithoutComments() | The local-part of the email address without comments | test |
| domain() | The domain of the email address | (world)example.one.com |
| domainWithoutComments() | The domain of the email address without comments | example.one.com |
| domainParts() | A list of the parts of the domain | [example, one, com] |
| displayName() | The display name of the email address, if it has one. | Optional.empty |
(For Admin , it would be Admin) |
||
| decodedDisplayName() | A fully MIME-decoded version of the display name of the email address, if it has one. | Optional.empty |
(For =?utf-8?q?te?xt?= , it would be te?xt) |
||
| comments() | A list of the comments in the email address | [hello, world] |
| explicitSourceRoutes() | A list of explicit source routes in the address, if present | [] |
(For @1st.relay,@2nd.relay:[email protected], it would be [1st.relay, 2nd.relay]) |
||
| isIpAddress() | Whether the domain is an IP address | false |
| containsWhitespace() | Whether the address contains obsolete whitespace | false |
| isAscii() | Whether the address contains only ASCII characters | true |
| hasDisplayName() | Whether the address has an display name | false |
| topLevelDomain() | The TopLevelDomain of the email address, or TopLevelDomain.OTHER if it is unknown |
TopLevelDomain.DOT_COM |
To create a new instance of Email from a string, use the tryParse(String email)
method, either the default version or on your own EmailValidator instance:
Optional parsed = JMail.tryParse("[email protected]");
Optional parsed = JMail.validator()
.disallowIpDomain()
.tryParse("[email protected]");Since tryParse(String email) returns an Optional, you can do
some cool things, such as:
String email = JMail.tryParse("invalidEmailString")
.map(Email::toString)
.orElse("[email protected]");JMail.tryParse("[email protected]")
.ifPresentOrElse(
email -> myEmailService.sendTo(email.toString()),
() -> log.error("Could not send email to invalid email"));// Get a normalized email address
Optional normalized = JMail.tryParse("admin(comment)@mysite.org")
.map(Email::normalized);
// normalized == Optional.of("[email protected]")// Get a normalized email address and remove any sub-addressing when normalizing
Optional normalized = JMail.tryParsNo open issues yet, or sync has not completed.