2

I am developing a system where any user can send his personal information like name, contact no and email in a form. There will be another portal from which we can retrieve those data and process. I am using Java web Technology in this regard.

Now my question is about the process I can validate an email address. This not only means whether the email address is badly formatted but also the availability of that email id.

That means if I input "abc@efg.hijk" which is completely well-formatted email id, but my system will check whether such an email address actually exists or not. If it exists I will store it in the database.

Thanks in advance for your support.

Thilina Dharmasena
  • 2,243
  • 2
  • 19
  • 27
Rashedur Rahman
  • 349
  • 4
  • 19
  • Possible duplicate of [What is the best Java email address validation method?](https://stackoverflow.com/questions/624581/what-is-the-best-java-email-address-validation-method) – George Z. Apr 28 '19 at 07:28
  • @GeorgeZ. I think the answer you post only talked format check – wl.GIG Apr 28 '19 at 07:31
  • 1
    The only check for _"availability of that email id"_ is sending an email and requiring people to click a confirmation link or enter a verification code. Anything else is either too broad or too restricting. – Mark Rotteveel Apr 28 '19 at 07:42
  • https://ux.stackexchange.com/q/70157/126567 check this – soheshdoshi Apr 28 '19 at 07:43

2 Answers2

4

You can easily google a format check code. Thus, we only talk about the existence check procedure.

  1. after format check, generate a verification code and store it.
  2. send the code to your target email.
  3. user fill the code, then compare them.
  4. store email address.
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
wl.GIG
  • 306
  • 1
  • 2
  • 13
0

The email validation can be done by the "SMTPMXLookup" class which I found from here. The following class can help you to find the validity of an email address:

public class SMTPMXLookup {

    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();

        
    }
    
    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 = (Attributes) 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 mailhost;
        String x = (String) en.next();
        String f[] = x.split( " " );
        //  THE fix *************
        if (f.length == 1)
            mailhost = f[0];
        else if ( f[1].endsWith( "." ) )
            mailhost = f[1].substring( 0, (f[1].length() - 1));
        else
            mailhost = f[1];
        //  THE fix *************            
        res.add( mailhost );
     }
     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 rgagnon.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
           ex.printStackTrace();
         }
         finally {
           if ( valid ) return true;
         }
     }
     return false;
     }

    
    

}
Rashedur Rahman
  • 349
  • 4
  • 19