MailValidUtil(引入commons-lang-2.6.jar、dnsjava-2.1.7.jar、fastjson-1.2.14.jar包)
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;
import com.alibaba.fastjson.JSONObject;
/**
*
* @项目名称: --
* @版权所有: --
* @技术支持: --
* @单元名称: 验证邮箱是否存在工具类
* @开始时间: 2017-10-17
* @开发人员: --
*/
public class MailValidUtil {
public static void main(String[] args) {
String email = "info@yiwaixiao.com";
System.out.println(MailValidUtil.valid(email));
}
// 邮箱域至少有一个.和两个单词,再严格点那么最后的顶级域至少要2个字母,最大呢?以域名“name”为准,那么最大就是4
private static Pattern emailPattern = Pattern
.compile("^(\\w)+([\\.\\-]?[\\w+]?)*@(\\w)+([\\.-]?\\w+)*((\\.\\w{2,4})+)$");
/**
* 验证邮箱是否存在,由于要读取IO,会造成线程阻塞
*
* @param email
* 要验证的邮箱
* @return 邮箱是否可达
*/
public static JSONObject valid(String email) {
JSONObject result = new JSONObject();
result.put("success", false);
result.put("code", 400);
result.put("msg", "邮箱不存在");
// 发出验证请求的域名(是当前站点的域名,可以任意指定)
String domain = "webmail120117.21gmail.com";
if (email == null || email.trim().isEmpty()) {
result.put("success", false);
result.put("code", 100);
result.put("msg", "邮箱不能为空");
return result;
}
if (!emailPattern.matcher(email).matches()) {
result.put("success", false);
result.put("code", 100);
result.put("msg", "邮箱格式不正确");
return result;
}
String host = email.split("@")[1];
if (domain.equals(host)) {
result.put("success", false);
result.put("code", 100);
result.put("msg", "主机域名不能和发出验证请求的域名[" + domain + "]一样");
return result;
}
Socket socket = new Socket();
InputStream is = null;
BufferedInputStream bis = null;
InputStreamReader isr = null;
BufferedReader bufferedReader = null;
OutputStream os = null;
OutputStreamWriter osw = null;
BufferedWriter bufferedWriter = null;
try {
// 查找mx记录,查找DNS缓存服务器上为MX类型的缓存域名信息
Record[] mxRecords = new Lookup(host, Type.MX).run();
if (mxRecords == null || mxRecords.length == 0) {
result.put("success", false);
result.put("code", 400);
result.put("msg", "查找不到MX记录");
return result;
}
// 邮件服务器地址
String mxHost = ((MXRecord) mxRecords[0]).getTarget().toString();
if (mxRecords.length > 1) { // 优先级排序
List<Record> arrRecords = new ArrayList<Record>();
Collections.addAll(arrRecords, mxRecords);
Collections.sort(arrRecords, new Comparator<Record>() {
public int compare(Record record, Record record2) {
return new CompareToBuilder().append(
((MXRecord) record).getPriority(),
((MXRecord) record2).getPriority())
.toComparison();
}
});
mxHost = ((MXRecord) arrRecords.get(0)).getTarget().toString();
}
// 开始smtp
socket.connect(new InetSocketAddress(mxHost, 25));
// 输入流
is = socket.getInputStream();
bis = new BufferedInputStream(is);
isr = new InputStreamReader(bis);
bufferedReader = new BufferedReader(isr);
// 输出流
os = socket.getOutputStream();
osw = new OutputStreamWriter(os);
bufferedWriter = new BufferedWriter(osw);
// 超时时间(毫秒)
long timeout = 6000;
// 睡眠时间片段(毫秒)
int sleepSect = 50;
// 相应码
int responseCode = 0;
responseCode = getResponseCode(timeout, sleepSect, bufferedReader);
// 连接(服务器是否就绪)
if (responseCode != 220) {
result.put("success", false);
result.put("code", 400);
result.put("msg", "连接邮箱服务器失败,服务器未就绪完毕");
return result;
}
// 握手
bufferedWriter.write("HELO " + domain + "\r\n");
bufferedWriter.flush();
responseCode = getResponseCode(timeout, sleepSect, bufferedReader);
if (responseCode != 250) {
result.put("success", false);
result.put("code", 400);
result.put("msg", "与邮箱服务器握手失败");
return result;
}
// 身份
bufferedWriter.write("MAIL FROM: <check@" + domain + ">\r\n");
bufferedWriter.flush();
responseCode = getResponseCode(timeout, sleepSect, bufferedReader);
if (responseCode != 250) {
result.put("success", false);
result.put("code", 400);
result.put("msg", "与邮箱服务器握手失败");
return result;
}
// 验证
bufferedWriter.write("RCPT TO: <" + email + ">\r\n");
bufferedWriter.flush();
responseCode = getResponseCode(timeout, sleepSect, bufferedReader);
if (responseCode != 250) {
result.put("success", false);
result.put("code", 400);
result.put("msg", "邮箱与邮箱服务器不可通信,邮箱不存在");
return result;
}
// 断开
bufferedWriter.write("QUIT\r\n");
bufferedWriter.flush();
result.put("success", true);
result.put("code", 200);
result.put("msg", "邮箱存在");
} catch (ConnectException e) {
result.put("success", false);
result.put("code", 100);
result.put("msg", "请求超时,请稍后重新尝试");
} catch (Exception e) {
e.printStackTrace();
result.put("success", false);
result.put("code", 500);
result.put(
"msg",
"请求异常,异常信息:" + e.getClass().getName() + "->"
+ e.getMessage());
} finally {
// 关闭资源
closeAll(result, socket, is, bis, isr, bufferedReader, os, osw,
bufferedWriter);
}
return result;
}
/** 读取响应码 */
private static int getResponseCode(long timeout, int sleepSect,
BufferedReader bufferedReader) throws InterruptedException,
NumberFormatException, IOException {
int code = 0;
for (long i = sleepSect; i < timeout; i += sleepSect) {
Thread.sleep(sleepSect);
if (bufferedReader.ready()) {
String outline = bufferedReader.readLine();
while (bufferedReader.ready()) {
bufferedReader.readLine();
}
//System.out.println(outline);
code = Integer.parseInt(outline.substring(0, 3));
break;
}
}
return code;
}
/** 关闭资源 */
private static void closeAll(JSONObject result, Socket socket,
InputStream is, BufferedInputStream bis, InputStreamReader isr,
BufferedReader bufferedReader, OutputStream os,
OutputStreamWriter osw, BufferedWriter bufferedWriter) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
result.put("success", false);
result.put("code", 500);
result.put("msg", "请求异常,异常信息:" + e.getClass().getName() + "->"
+ e.getMessage());
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
result.put("success", false);
result.put("code", 500);
result.put("msg", "请求异常,异常信息:" + e.getClass().getName() + "->"
+ e.getMessage());
}
}
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
result.put("success", false);
result.put("code", 500);
result.put("msg", "请求异常,异常信息:" + e.getClass().getName() + "->"
+ e.getMessage());
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
result.put("success", false);
result.put("code", 500);
result.put("msg", "请求异常,异常信息:" + e.getClass().getName() + "->"
+ e.getMessage());
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
result.put("success", false);
result.put("code", 500);
result.put("msg", "请求异常,异常信息:" + e.getClass().getName() + "->"
+ e.getMessage());
}
}
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
result.put("success", false);
result.put("code", 500);
result.put("msg", "请求异常,异常信息:" + e.getClass().getName() + "->"
+ e.getMessage());
}
}
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException e) {
result.put("success", false);
result.put("code", 500);
result.put("msg", "请求异常,异常信息:" + e.getClass().getName() + "->"
+ e.getMessage());
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
result.put("success", false);
result.put("code", 500);
result.put("msg", "请求异常,异常信息:" + e.getClass().getName() + "->"
+ e.getMessage());
}
}
}
}