LoginSignup
4

More than 5 years have passed since last update.

javaでメールアドレスのMXレコードを調べてドメインチェックする

Last updated at Posted at 2017-09-19

WEBでメール受付~とかやってると
正しいメールに混じってスパムメールが数多く飛んでくるかと思います。

メールを受け付けた後に「受付完了!」のメールを返信しようとしても
スパム相手だと
そんなアドレスないよ!とエラーリターンの山が積まれていくのを見ていく日々・・・
コレなんとかならないの?!

メールアドレスの@マークの前部分はユーザに該当しちゃうので
送ってみないと分からないのですが

少なくとも
@マークの後ろ部分は本当に存在するドメインなのかチェックしよう!

ということが昔あり、javaで組んだ感じです。

特に説明はないです。

import java.util.Hashtable;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class MXLookup {
    public static void main(String[] args) {
        exec("yahoo.jp");
        exec("yahoo.co.jp");
        exec("126.com");
        exec("127.com");
    }
    private static void exec(String hostname) {
        System.out.println( hostname + " : " + doLookup( hostname ) + "" );
    }
    private static String doLookup( String hostName ) {
        try {
            Hashtable<String,String> env = new Hashtable<String,String>();
            env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
            DirContext ictx = new InitialDirContext( env );
            Attributes attrs = ictx.getAttributes( hostName, new String[] { "MX" });
            Attribute attr = attrs.get( "MX" );
            if( attr == null ){
                return null;
            }
            StringBuilder sb = new StringBuilder();
            for(int i=0;i<attr.size();i++){
                if(sb.length() > 0){
                    sb.append(", ");
                }
                sb.append(attr.get(i));
            }
            return sb.toString();
        } catch (NamingException e) {
            return null;
        }
    }

}

ちなみに作成したシステムは
受信メールをシェルに食わせる
でメールを受信したタイミングでキックされるシェルからこのJavaが呼ばれ
メール送信者のフィルタリングをする感じです。

以上です
ご参考になれば。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4