验证邮箱是否存在工具类

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());
			}
		}
	}

}


C#验证Email是否真正存在 在以往的编程中,比如编写用户的资料时,有时需要确认用户输入的Email是否真实有效,以前我们最多只能做到验证Email是否包含了某些特殊的字符,比如"@",".",".com"等,做到的只是判断了Email的合法性,证明用户填写的Email格式是正确的,但是这个Email是否真正的存在于网络中,则没有办法。  首先需要大家了解一下SMTP协议。 1.SMTP是工作在两种情况下:一是电子邮件从客户机传输到服务器;二是从某一个服务器传输到另一个   服务器 2.SMTP是个请求/响应协议,命令和响应都是基于ASCII文本,并以CR和LF符结束。响应包括一个表示返    回状态的三位数字代码 3.SMTP在TCP协议25号端口监听连接请求 4.连接和发送过程 SMTP协议说复杂也不复杂(明明带有“简单”这个词嘛),说简单如果你懂得Sock。不过现在只是我们利用的就是第一条中说的,从客户机传输到服务器,当我们向一台服务器发送邮件时,邮件服务器会首先验证邮件发送地址是否真的存在于本服务器上。 操作的步骤如下: 连接服务器的25端口(如果没有邮件服务,连了也是白连) 发送helo问候 发送mail from命令,如果返回250表示正确可以,连接本服务器,否则则表示服务器需要发送人验证。 发送rcpt to命令,如果返回250表示则Email存在 发送quit命令,退出连接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值