这是我身边的东西。为了检查地址是否是有效的格式,这里有一个regex来验证它是否接近rfc2822(它没有捕捉到一些奇怪的角落情况)。我去年在网上找到的。
private static final Pattern rfc2822 = Pattern.compile(
"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"
);
if (!rfc2822.matcher(email).matches()) {
throw new Exception("Invalid address");
}
这将处理简单的语法(大部分)。我知道的另一个检查将让您检查域是否有MX记录。看起来是这样的:
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(domainName, new String[] {"MX"});
Attribute attr = attrs.get("MX");
if (attr == null)
// No MX record
else
// If attr.size() > 0, there is an MX record
这个,我也在网上找到了。它来自
this link
如果这两个都通过,你就很有可能有一个有效的地址。如果地址是自己的(不只是域名),它没有满,等等。。。你真的查不出来。
注意第二张支票是
时间密集型
希望这有帮助。
编辑
我想指出的是,至少有比regex更好的方法来检查基本有效性。Don和Michael指出Apache Commons有一些东西,我最近发现可以在InternetAddress上使用.validate()让Java检查地址是否真的是RFC-8222,这肯定比我的regex更准确。