驗證郵件的有效性

public static boolean checkEmail(String email) {
if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
return false;
}

String host = "";
String hostName = email.split("@")[1];
Record[] result = null;
SMTPClient client = new SMTPClient();

try {
// 查找MX記錄
Lookup lookup = new Lookup(hostName, Type.MX);
lookup.run();
if (lookup.getResult() != Lookup.SUCCESSFUL) {
return false;
} else {
result = lookup.getAnswers();
}

// 連接到郵箱服務器
for (int i = 0; i < result.length; i++) {
host = result[i].getAdditionalName().toString();
client.connect(host);
if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
client.disconnect();
continue;
} else {
break;
}
}

//以下2項自己填寫快速的,有效的郵箱
client.login("163.com");
client.setSender("[email protected]");
client.addRecipient(email);
if (250 == client.getReplyCode()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
}
}
return false;
}

需要的jar支持:commons-net-2.2.jar,dnsjava-2.1.1.jar

此方式優點:驗證出的結果,完全符合真實情況,如果一個郵箱被驗證存在,那麼它就一定存在,反之亦然。

此方式缺點:驗證時比較耗時,我自己檢測,需要5秒左右的時耗;實際情況視你自己寫的發件方而定。

核心代碼:

public static boolean checkEmail(String email) throws DNSLookupException {
if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
return false;
}
IsEMailResult result = IsEMail.is_email_verbose(email, true);
switch (result.getState()) {
case OK:
return true;
default:
return false;
}
}

需要的jar支持:IsEMail.jar

此方式優點:驗證時耗時短,我自己檢測,幾乎立刻就可以獲得結果。

此方式缺點:驗證出的結果,基本符合真實情況;此方式驗證的只是郵箱表示的站點是否存在,至於郵箱是否真實存在則不一定。如***@gmail.com格式的郵箱,則全部驗證存在,但實際情況則並非如此;但提供此種郵箱服務的google站點卻的確真實存在。
發佈了104 篇原創文章 · 獲贊 1 · 訪問量 5757
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章