邮箱有效性多种验证方式

邮箱有效性验证

  • 情景
  • 实现方法
    • Lookup,SMTPClient
    • 邮箱验证网站
    • IsEMailResult
      • IsEMailResult 本体使用
      • EmailValidator使用
    • 其他
      • Apache Commons Validator

情景

系统上发送离职人邮箱报错,要求发送时过滤掉离职人邮箱。
下图是发送到离职人邮箱的提示:
邮箱有效性多种验证方式_第1张图片

实现方法

Lookup,SMTPClient

这个方法准确率高,离职人邮箱可以过滤掉

下载jar包或者写入依赖:commons-net-3.6.jardnsjava-2.1.9.jar

public static boolean checkEmail(String email) {
		if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
			logger.info(email + "邮箱match失败!");
			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) {
				logger.info(email + "邮箱lookup失败!" + lookup.getResult());
				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项login和setSender自己填写快速的,有效的邮箱
			if (!"XXX.com".equals(hostName)) {
				client.login("XXX.com");
				client.setSender("[email protected]");
			} else {
				client.login("qq.com");
				client.setSender("[email protected]");
			}
			client.addRecipient(email);
			if (250 == client.getReplyCode()) {
				return true;
			}
			logger.info(email + "邮箱回复码:" + client.getReplyCode());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(email + "邮箱有效验证报错:" + e);
			return false;
		} finally {
			try {
				client.disconnect();
			} catch (IOException e) {
			}
		}
		return false;
	}

client.login()填写hostname,发送人hostname和接收人emailhostname一致,出来的结果不管是否有效都是falseReplyCode451(ACTION_ABORTED) 或者 报错(如果发送人和接收人邮箱一样部分会报错)。
报错

org.apache.commons.net.smtp.SMTPConnectionClosedException: Connection closed without indication.
	at org.apache.commons.net.smtp.SMTP.__getReply(SMTP.java:198)
	at org.apache.commons.net.smtp.SMTP.__sendCommand(SMTP.java:170)
	at org.apache.commons.net.smtp.SMTP.__sendCommand(SMTP.java:185)
	at org.apache.commons.net.smtp.SMTP.rcpt(SMTP.java:528)
	at org.apache.commons.net.smtp.SMTPClient.addRecipient(SMTPClient.java:315)
	at cn.iot.utils.MailRelated.checkEmail(MailRelated.java:97)
	at cn.iot.utils.MailRelated.main(MailRelated.java:118)

邮箱验证网站

准确率高

国外的验证邮箱网站
登录后,单个邮箱验证只能免费2000个邮箱,Maximum 50,000 emails per list

API使用

public static boolean checkEmail2(String email) throws Exception {
		// 单个邮箱登录后只能免费用2000个邮箱判断,50000
		String key = ""; // 注册后就会有key值
		String resulString = HttpClientUtil
				.doGet("https://app.verify-email.org/api/v1/"+key+"/verify/"
						+ email);
		JSONObject resultJson = JSONObject.parseObject(resulString);
		String result = resultJson.getString("status_description");
		System.out.println(result);
		if (result.contains("OK")) {
			return true;
		}
		return false;
	}

API返回的JSON

{
    "email": "[email protected]",
    "status": 1,
    "status_description": "OK email",
    "smtp_code": 250,
    "smtp_log": "250 2.1.5 OK u8-v6si8965853qvh.5 - gsmtp\r\n"
}

status_description现在测试遇到三种,OK emailUNKNOW emailBAD email

离职人邮箱返回BAD email

IsEMailResult

离职邮箱过滤不掉,返回true。准确率低

IsEMailResult 本体使用

ok是true,error和warning都是false。

public static boolean checkEmail1(String email) throws Exception {
		// 离职人的邮箱仍返回true
		if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
			return false;
		}
		IsEMailResult result = IsEMail.is_email_verbose(email, true); // 使用要添加IsEMail.jar
		switch (result.getState()) {
		case OK: 
			return true;
		default: // WARNING,ERROR
			return false;
		}
	}

EmailValidator使用

下面方法的核心也是IsEMailResult。ok和warning都是true,error是false。比上面IsEMailResult准确率更低

public static boolean checkEmail1(String email) throws Exception {
		// 离职人的邮箱仍返回true
		if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
			return false;
		}
		EmailValidator emailValidator = new IsEmailEmailValidator();
		EmailValidationResult result = emailValidator.validate(email);
		// result.getState().isValid();// ok和warning都是true,error是false
		// result.getReason(); // 原因
		return result.getState().isValid();
	}

		
	    <dependency>
	      <groupId>com.github.lite2073groupId>
	      <artifactId>email-validatorartifactId>
	      <version>1.0version>
	   dependency>

其他

Apache Commons Validator

需要的jar:commons-validatorjavax.mail.internet
测试离职人员和unknown email,返回true

 boolean flag = EmailValidator.getInstance().isValid(email);
 InternetAddress internetAddress = new InternetAddress(email);
 internetAddress.validate(); // AddressException - if the address isn't valid.

你可能感兴趣的:(邮箱,Java)