這是我身邊的東西。為了檢查位址是否是有效的格式,這裡有一個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更準确。