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


当前回答

您想验证什么?电子邮件地址?

只能检查电子邮件地址的格式是否符合要求。参见标准:RFC2822。最好的方法是使用正则表达式。如果不发一封邮件,你永远不会知道是否真的存在。

我检查了公共验证器。它包含一个org.apache.commons.validator.EmailValidator类。看起来是个不错的起点。

其他回答

可以像其他答案中提到的那样使用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);

回答迟了,但我觉得简单而有价值:

    public boolean isValidEmailAddress(String email) {
           String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
           java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
           java.util.regex.Matcher m = p.matcher(email);
           return m.matches();
    }

测试用例:

出于生产目的,域名验证应该在网络上执行。

您想验证什么?电子邮件地址?

只能检查电子邮件地址的格式是否符合要求。参见标准:RFC2822。最好的方法是使用正则表达式。如果不发一封邮件,你永远不会知道是否真的存在。

我检查了公共验证器。它包含一个org.apache.commons.validator.EmailValidator类。看起来是个不错的起点。

Apache Commons通常被认为是一个可靠的项目。但是请记住,如果你想确保它是一个真实的电子邮件,并且所有者希望它在你的网站上使用,你仍然需要发送一封验证邮件到这个地址。

编辑:有一个错误,它对域名的限制太大,导致它不接受来自新顶级域名的有效电子邮件。 此错误已于03/Jan/15 02:48在common -validator版本1.4.1中解决

当前的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.