Java 根据邮箱获取对应的 MX 记录值

2020-04-21 10:06:53

根据邮箱地址来确定邮箱服务商所在域名的 MX 记录值 可用于发送匿名邮件时指定 Host,Demo 示例如下: ``` package demo.test; import org.junit.Test; import javax.naming.Context; 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 java.util.Hashtable; public class TestDemo { @Test public void testDns() throws NamingException { System.out.println(getMxHost("test@yeah.net", null)); System.out.println(getMxHost("test@163.net", null)); System.out.println(getMxHost("test@fiebug.com", null)); System.out.println(getMxHost("test@qq.com", "8.8.8.8")); } public String getMxHost(String email, String dns) { try { // 设置 DNS 服务器 if (dns == null) { dns = "dns://"; } else { dns = "dns://" + dns; } // 获取邮件地址中的域名 String[] emailArr = email.split("@"); if (emailArr.length != 2) { throw new RuntimeException("email address error."); } String domain = emailArr[1]; // 通过 DNS 获取域名 MX 记录 Hashtable env = new Hashtable<>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); env.put(Context.PROVIDER_URL, dns); DirContext dirContext = new InitialDirContext(env); Attributes attributes = dirContext.getAttributes(domain, new String[]{"MX"}); // 取出一组 MX 记录中第一个 Attribute mxAttribute = attributes.get("MX"); if (mxAttribute == null || mxAttribute.size() <= 0) { return null; } String mxHost = StringUtils.valueOf(mxAttribute.get()); return mxHost.replaceAll("\\d+ (.+)\\.", "$1"); } catch (NamingException e) { return null; } } } ```

分类:编程     关键词:域名,MX

评论(0) 浏览(87)