Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Friday, October 14, 2022

Check an email exist using JAVA- Java email verification and validation

 

This tutorial shows how to check an email exist using JAVA. This program works with the principle of Mail Exchange(MX) look up. Detailed documentation is shown in this page here. I cannot assure you the efficiency of this code. The result of the test will depend on the domain of emails since some domains will not share the MX record info for anonymous requests.

  1. Project structure in Eclipse is shown,
  2. validate_code_source.java
    package email;
    import java.io.*;
    import java.net.*;
    import java.util.*; 
    import javax.naming.*; 
    import javax.naming.directory.*;
    public class validate_code_source {
    	 public static void main( String args[] ) {
    	      String testData[] = {
    	    		  "jinujawad6s@gmail.com", 
    	    		  "drp@drp.cz",
    	    		  "tvf@tvf.cz",
    	    		  "info@ermaelan.com",
    	    		  "drp@drp.cz",
    	    		  "begeddov@jfinity.com",
    	    		  "vdv@dyomedea.com",
    	    		  "me@aaronsw.com",
    	    		  "aaron@theinfo.org",
    	    		  "rss-dev@yahoogroups.com",
    	    		  "tvf@tvf.cz",
    	          };
    	      for ( int ctr = 0 ; ctr < testData.length ; ctr++ ) {
    	         System.out.println( testData[ ctr ] + " is valid? " + 
    	               isAddressValid( testData[ ctr ] ) );
    	      }
    	      return;
    	      }
        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: <tim@orbaker.com>" );
                  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  String call_this_to_validate( String email ) {
            String testData[] = {email};
            String return_string="";
            for ( int ctr = 0 ; ctr < testData.length ; ctr++ ) {
            	return_string=( testData[ ctr ] + " is valid? " + 
                     isAddressValid( testData[ ctr ] ) );
            }
            return return_string;
            }
    }
    
  3. Output is as Shown
  4. index.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%@page import="email.validate_code_source"%><html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Check email is valid</title>
    </head>
    <body>
    <center>
     <h2>Check if email id exists using JAVA</h2>
     <form action="index.jsp">
     Email : <input type="text" name="email"> <input type="submit" value="Check">
     </form>
     <br>
     <%
     String email=(String)request.getParameter("email");
     if(email!=null){
     validate_code_source obj_validate_code_source=new validate_code_source();
     boolean exists=obj_validate_code_source.isAddressValid(email);
     if(exists==true){
     %>
     <h3><%=email %> : Exist </h3> 
     <% 
     }else{
     %>
     <h3><%=email %> : Does not Exist </h3> 
     <% 
     }
     }
     %>
    </center>
    </body>
    </html>
    

No comments:

Post a Comment