Java中有哪些好的电子邮件地址验证库?有任何替代公共验证器的方法吗?


当前回答

如果您希望验证电子邮件地址是否有效,那么VRFY将为您提供一些方法。我发现它对于验证内网地址(即内部站点的电子邮件地址)很有用。然而,它对互联网邮件服务器的用处不大(请参阅本页顶部的警告)

其他回答

尽管有许多替代Apache commons的方法,但它们的实现充其量只是基本的(就像Apache commons的实现本身一样),在其他情况下甚至是完全错误的。

我也会远离所谓的简单的“非限制性”正则表达式;没有这样的事。例如,@根据上下文被允许多次使用,你怎么知道需要的那个在那里?简单的正则表达式无法理解它,即使电子邮件应该是有效的。任何更复杂的东西都很容易出错,甚至包含隐藏的性能杀手。你要怎么维护这样的东西?

我所知道的唯一一个全面的RFC兼容的基于regex的验证器是email-rfc2822-validator,它的“精炼”regex适当地命名为Dragons.java。它只支持较旧的RFC-2822规范,尽管它足够满足现代需求(RFC-5322在日常使用范围之外的地方更新了它)。

但真正需要的是一个词法分析器,它可以正确地解析字符串,并根据RFC语法将其分解为组件结构。EmailValidator4J在这方面似乎很有前途,但仍然很年轻,而且有局限性。

另一种选择是使用webservice,比如Mailgun经过实战测试的验证webservice或Mailboxlayer API(只使用第一个谷歌结果)。它不是严格的RFC兼容,但是对于现代需求来说已经足够好了。

似乎没有任何完美的库或方法可以自己做到这一点,除非您必须有时间向电子邮件地址发送电子邮件并等待回复(尽管这可能不是一个选项)。我最终使用了这里的一个建议http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/,并调整了代码,使其可以在Java中工作。

public static boolean isValidEmailAddress(String email) {
    boolean stricterFilter = true; 
    String stricterFilterString = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    String laxString = ".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
    String emailRegex = stricterFilter ? stricterFilterString : laxString;
    java.util.regex.Pattern p = java.util.regex.Pattern.compile(emailRegex);
    java.util.regex.Matcher m = p.matcher(email);
    return m.matches();
}

可以像其他答案中提到的那样使用Apache Commons验证器。

pom.xml:

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.4.1</version>
</dependency>

build.gradle:

compile 'commons-validator:commons-validator:1.4.1'

导入:

import org.apache.commons.validator.routines.EmailValidator;

代码:

String email = "myName@example.com";
boolean valid = EmailValidator.getInstance().isValid(email);

并允许本地地址

boolean allowLocal = true;
boolean valid = EmailValidator.getInstance(allowLocal).isValid(email);

Les Hazlewood使用Java正则表达式编写了一个非常完整的符合RFC 2822的电子邮件验证器类。你可以在http://www.leshazlewood.com/?p=23上找到它。然而,它的彻底性(或Java RE实现)导致效率低下——阅读关于长地址解析时间的注释。

当前的Apache Commons Validator版本为1.3.1。

进行验证的类是org.apache.commons.validator.EmailValidator。它导入了org.apache.oro.text.perl。Perl5Util来自一个退役的雅加达ORO项目。

BTW, I found that there is a 1.4 version, here are the API docs. On the site it says: "Last Published: 05 March 2008 | Version: 1.4-SNAPSHOT", but that's not final. Only way to build yourself (but this is a snapshot, not RELEASE) and use, or download from here. This means 1.4 has not been made final for three years (2008-2011). This is not in Apache's style. I'm looking for a better option, but didn't find one that is very adopted. I want to use something that is well tested, don't want to hit any bugs.