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


当前回答

下面是我的实用方法,我只需要使用RFC中允许的字符合理地区分blah@domain地址。地址必须事先转换为小写。

public class EmailAddressValidator {

    private static final String domainChars = "a-z0-9\\-";
    private static final String atomChars = "a-z0-9\\Q!#$%&'*+-/=?^_`{|}~\\E";
    private static final String emailRegex = "^" + dot(atomChars) + "@" + dot(domainChars) + "$";
    private static final Pattern emailPattern = Pattern.compile(emailRegex);

    private static String dot(String chars) {
        return "[" + chars + "]+(?:\\.[" + chars + "]+)*";
    }

    public static boolean isValidEmailAddress(String address) {
        return address != null && emailPattern.matcher(address).matches();
    }

}

其他回答

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.

这是最好的方法:

public static boolean isValidEmail(String enteredEmail){
        String EMAIL_REGIX = "^[\\\\w!#$%&’*+/=?`{|}~^-]+(?:\\\\.[\\\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,6}$";
        Pattern pattern = Pattern.compile(EMAIL_REGIX);
        Matcher matcher = pattern.matcher(enteredEmail);
        return ((!enteredEmail.isEmpty()) && (enteredEmail!=null) && (matcher.matches()));
    }

来源: http://howtodoinjava.com/2014/11/11/java-regex-validate-email-address/

http://www.rfc-editor.org/rfc/rfc5322.txt

似乎没有任何完美的库或方法可以自己做到这一点,除非您必须有时间向电子邮件地址发送电子邮件并等待回复(尽管这可能不是一个选项)。我最终使用了这里的一个建议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();
}

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