package com.action;
import java.io.IOException;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;
public class mail {
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("sxgkwei@163.com");
client.addRecipient(email);
if (250 == client.getReplyCode()) {
return true;
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
client.disconnect();
}
catch (IOException e) {
}
}
return false;
}
public static void main(String[] args) {
boolean test = checkEmail("6556565656@qq.com");
if (test) {
System.out.print("有效");
}
else System.out.print("无效");
}
}
需要的jar支持:commons-net-2.2.jar,dnsjava-2.1.1.jar 此方式优点:验证出的结果,完全符合真实情况,如果一个邮箱被验证存在,那么它就一定存在,反之亦然。 此方式缺点:验证时比较耗时,我自己检测,需要5秒左右的时耗;实际情况视你自己写的发件方而定。