通过socket、smtp验证邮箱是否存在
-
验证逻辑图
-
验证邮箱代码
/*** socket验证** @param mail 邮箱* @return*/private static Boolean smtpVerify(String mail) {Socket socket = null;boolean valid;BufferedReader reader = null;BufferedWriter writer = null;// 获取邮箱的域名// 1、获取邮箱域名int pos = mail.indexOf('@');if (pos == -1) {return false;}String hostname = mail.substring(++pos);try {int resp;// socket 验证邮箱服务器 25端口socket = new Socket(hostname, 25);reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));resp = smtpResp(reader);if (resp != 220) {return false;}smtpExce(writer, "EHLO 1234@outlook.com");resp = smtpResp(reader);if (resp != 250) {// 不是smtpreturn false;}// 验证MAIL fromsmtpExce(writer, "MAIL FROM: <1234@outlook.com>");resp = smtpResp(reader);if (resp != 250) {throw new Exception("Sender rejected");}// 验证RCPT TOsmtpExce(writer, "RCPT TO: <" + mail + ">");resp = smtpResp(reader);// 重置会话,当前传输被取消smtpExce(writer, "RSET");smtpResp(reader);// 取消smtpExce(writer, "QUIT");smtpResp(reader);if (resp != 250) {return false;}valid = true;} catch (Exception ex) {return false;} finally {// 关闭连接try {if (reader != null) {reader.close();}if (writer != null) {writer.close();}if (socket != null) {socket.close();}} catch (Exception e) {}}return valid;}
- 发送smtp 命令的方法
/*** 执行smtp 命令** @param wr* @param smtpCmd smtp 命令* @throws IOException*/private static void smtpExce(BufferedWriter wr, String smtpCmd) throws IOException {wr.write(smtpCmd + "\r\n");wr.flush();return;}
- 接收smtp响应方法
/*** 获取smtp命令执行结果** @param in* @return* @throws IOException*/private static int smtpResp(BufferedReader in) throws IOException {String line = null;int respCode = 0;while ((line = in.readLine()) != null) {String statusCode = line.substring(0, 3);try {respCode = Integer.parseInt(statusCode);} catch (Exception ex) {respCode = -1;}if (line.charAt(3) != '-') {break;}}return respCode;}
- 验证一下邮箱是否存在
public static void main(String[] arg) {String email = "1234@163.com";boolean vaild = smtpVerifyMail(email);if (vaild) {System.out.println(email + "邮箱不存在");} else {System.out.println(email + "邮箱真实存在");}}
- 验证邮箱结果