RubyPDF Blog Java,tutorial Lookup using MX record to validate mail server

Lookup using MX record to validate mail server

The best you can do to verify if an email address is real is to verify if there is a mail server registered to the domain name.

import  java.util.Hashtable;
import  javax.naming.*;
import  javax.naming.directory.*;

public class MXLookup {
  public static void main( String args[] ) {
    if( args.length == 0 ) {
      System.err.println( "Usage: MXLookup host [...]" );
      System.exit( 99 );
    }
    for( int i = 0; i < args.length; i++ ) {
      try {
        System.out.println( args[i] + " has " +
          doLookup( args[i] ) + " mail servers" );
      }
      catch( Exception e ) {
        System.out.println(args[i] + " : " + e.getMessage());
      }
    }
  }

  static int doLookup( String hostName ) throws NamingException {
    Hashtable env = new Hashtable();
    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( 0 );
    return( attr.size() );
  }
}

The output is

<java MXLookup rgagnon.com realhowto.com
rgagnon.com has 1 mail servers
realhowto.com : DNS name not found [response code 3]

From T. Orbaker, more infos on that subject (thanks to him).

There are other methods by which to validate an email address to a higher degree of than just the mail server.

One:
Use the VRFY command (see RFCs 821/2821). Because this was abused by spammers, it have typically been disabled on most mail servers. Some recent servers don't even support this command as they are so frequently shut off.

When it works, connect to the server, issue the HELO command and then send 'VRFY '. If it is enabled, and the address is valid, you should get a 250 if the address is valid and a 550 if it isn't. Note that some servers (qmail) return 252 as a means of pleading the fifth. Others will return a failure even if the address exists but the command has been disables (although this is typically a 450 error).

Two (better method):
Connect to the servers determined by your code snippet. BUT (and the code below doesn't do this) they must be tried from lowest preference to highest to be absolutely correct.

Once you have connected, you create the SMTP envelope, but you don't put anything in it. This is the point at which most servers will give up the dirt on whether or not an address is valid. If an envelope cannot be built, we know that the address is invalid.

The reason for connecting in order of preference:

Imagine ABC company has an Internet conneciton and runs their own mail server for abc.com. To prevent bounces and other mail errors if their connection or server should be down, their provider isp.com agrees to set up a 'store and forward' scheme for their mail. If abc.com is not available, then isp.com gets the message and when abc.com is again available, the message gets forwarded. The MX records would look something like:
MX 1 abc.com
MX 5 isp.com

Now, imagine that you connect to isp.com and try to send a message. The mail server at isp.com doesn't have the actual user list to know which addresses are valid, it just accepts everything and relies on abc.com to sort out the bounces.

If these are not checked in the proper order, there will be no errors for invalid addresses.

Yahoo appears to use a store and forward mechanism to its own internal servers, thus conclusively verifying a yahoo address is not possible. I suspect that hotmail is the same.

It is not possible to verify an address on a domain that uses a catch-all account as the catch account will receive the mail (it does, however, mean that someone will at least SEE the message).

import java.io.*;
import java.net.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class SMTP {
    private static int hear( BufferedReader in ) throws IOException {
      String line = null;
      int res = 0;

      while ( (line = in.readLine()) != null ) {
          String pfx = line.substring( 0, 3 );
          try {
             res = Integer.parseInt( pfx );
          } 
          catch (Exception ex) {
             res = -1;
          }
          if ( line.charAt( 3 ) != '-' ) break;
      }

      return res;
      }

    private static void say( BufferedWriter wr, String text ) 
       throws IOException {
      wr.write( text + "\r\n" );
      wr.flush();

      return;
      }
    
    private static ArrayList getMX( String hostName )
          throws NamingException {
      // Perform a DNS lookup for MX records in the domain
      Hashtable env = new Hashtable();
      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 we don't have an MX record, try the machine itself
      if (( attr == null ) || ( attr.size() == 0 )) {
        attrs = ictx.getAttributes( hostName, new String[] { "A" });
        attr = attrs.get( "A" );
        if( attr == null ) 
             throw new NamingException
                      ( "No match for name '" + hostName + "'" );
      }

      // Huzzah! we have machines to try. Return them as an array list
      // NOTE: We SHOULD take the preference into account to be absolutely
      //   correct. This is left as an exercise for anyone who cares.
      ArrayList res = new ArrayList();
      NamingEnumeration en = attr.getAll();

      while ( en.hasMore() ) {
         String x = (String) en.next();
         String f[] = x.split( " " );
         if ( f[1].endsWith( "." ) ) 
             f[1] = f[1].substring( 0, (f[1].length() - 1));
         res.add( f[1] );
      }
      return res;
      }

    public static boolean isAddressValid( String address ) {
      // Find the separator for the domain name
      int pos = address.indexOf( '@' );

      // If the address does not contain an '@', it's not valid
      if ( pos == -1 ) return false;

      // Isolate the domain/machine name and get a list of mail exchangers
      String domain = address.substring( ++pos );
      ArrayList mxList = null;
      try {
         mxList = getMX( domain );
      } 
      catch (NamingException ex) {
         return false;
      }

      // Just because we can send mail to the domain, doesn't mean that the
      // address is valid, but if we can't, it's a sure sign that it isn't
      if ( mxList.size() == 0 ) return false;

      // Now, do the SMTP validation, try each mail exchanger until we get
      // a positive acceptance. It *MAY* be possible for one MX to allow
      // a message [store and forwarder for example] and another [like
      // the actual mail server] to reject it. This is why we REALLY ought
      // to take the preference into account.
      for ( int mx = 0 ; mx < mxList.size() ; mx++ ) {
          boolean valid = false;
          try {
              int res;
              Socket skt = new Socket( (String) mxList.get( mx ), 25 );
              BufferedReader rdr = new BufferedReader
                 ( new InputStreamReader( skt.getInputStream() ) );
              BufferedWriter wtr = new BufferedWriter
                 ( new OutputStreamWriter( skt.getOutputStream() ) );

              res = hear( rdr );
              if ( res != 220 ) throw new Exception( "Invalid header" );
              say( wtr, "EHLO orbaker.com" );

              res = hear( rdr );
              if ( res != 250 ) throw new Exception( "Not ESMTP" );

              // validate the sender address  
              say( wtr, "MAIL FROM: " );
              res = hear( rdr );
              if ( res != 250 ) throw new Exception( "Sender rejected" );

              say( wtr, "RCPT TO: <" + address + ">" );
              res = hear( rdr );

              // be polite
              say( wtr, "RSET" ); hear( rdr );
              say( wtr, "QUIT" ); hear( rdr );
              if ( res != 250 ) 
                 throw new Exception( "Address is not valid!" );

              valid = true;
              rdr.close();
              wtr.close();
              skt.close();
          } 
          catch (Exception ex) {
            // Do nothing but try next host
          } 
          finally {
            if ( valid ) return true;
          }
      }
      return false;
      }

    public static void main( String args[] ) {
      String testData[] = {
          "tim@orbaker.com", // Valid address
          "fail.me@nowhere.spam", // Invalid domain name
          "arkham@bigmeanogre.net", // Invalid address
          "nosuchaddress@yahoo.com" // Failure of this method
          };

      for ( int ctr = 0 ; ctr < testData.length ; ctr++ ) {
         System.out.println( testData[ ctr ] + " is valid? " + 
               isAddressValid( testData[ ctr ] ) );
      }
      return;
      }
}

from http://www.rgagnon.com/javadetails/java-0452.html

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.