필요 라이브러리
<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.8.0</version>
</dependency>
코드(java ver)
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.validator.routines.EmailValidator;
public class CheckEmailDomainSample {
/** 알고있는 유효한 이메일 호스트명 */
private static final Set<String> CACHED_VALID_HOSTNAME = Sets.newLinkedHashSet(Arrays.asList("gmail.com", "naver.com"));
private static final String targetFilePath = "검사할 도메인이 저장된 파일 경로(개행 구분)";
private static final EmailValidator emailValid = EmailValidator.getInstance();
public static void main(String[] args) throws IOException {
List<String> emailDomainList = FileUtils.readLines(new File(targetFilePath));
for (String hostname : emailDomainList) {
System.out.println(String.format("%s : %s'", hostname, isValidHostname(hostname)));
}
}
public static boolean isValidHostname(String hostname) {
try {
if (CACHED_VALID_HOSTNAME.contains(StringUtils.lowerCase(hostname))) {
return true;
}
final String mxStr = "MX";
Hashtable<String, String> hashtable = new Hashtable<>();
hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
hashtable.put("com.sun.jndi.dns.timeout.initial", "5000"); /* quite short... too short? */
hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
DirContext ictx = new InitialDirContext(hashtable);
Attributes attrs = ictx.getAttributes(hostname, new String[]{mxStr});
Attribute attr = attrs.get(mxStr);
if (attr == null || attr.size() == 0) {
return false; //없음
}
NamingEnumeration e = attr.getAll();
while (e.hasMore()) {
String mxs = String.valueOf(e.next());
String[] mx = mxs.split("\\s+");
for (String mxString : mx) {
if (StringUtils.endsWith(mxString, ".")) {
return true;
}
}
}
} catch (NamingException ne) {
return false;
}
return false;
}
}