引入依赖
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/dnsjava/dnsjava -->
<dependency>
<groupId>dnsjava</groupId>
<artifactId>dnsjava</artifactId>
<version>2.1.1</version>
</dependency>
测试代码
public static void main(String[] args) {
System.out.println(checkEmail("验证邮箱"));
}
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 {
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;
}
}
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;
}