0

quisiera saber si se pueden validar que exista un correo proporcionado.

Hasta ahorita tengo todo ya hecho puedo validar todos los correos excepto los de hotmail, estoy usando mail exchange.

pero pues no me valida los correos hotmail aunque obtenga un servidor este me indica que el correo es falso.

Este es el código que he estado probando hasta ahorita, el cual valida si un correo existe o no, el único inconveniente es que no valida los correos de hotmail así como tampoco outlook.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package testreadsharefolder;

//import java.io.BufferedReader;
//import java.io.BufferedWriter;
//import java.io.InputStreamReader;
//import java.io.OutputStreamWriter;
//import java.net.Socket;
//import java.util.ArrayList;
//import java.util.Hashtable;
//import javax.naming.NamingException;
//import javax.naming.directory.DirContext;
//import javax.naming.directory.InitialDirContext;

import java.io.*;
import java.net.*;
import java.util.*; 
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.naming.*; 
import javax.naming.directory.*;


/**
 *
 * @author facv_
 * //File archivo = new File("\\\\LAPTOP-SR35DQ5L\\Users\\itzca\\OneDrive\\Documentos\\ArchivosCompartidos\\Prueba.txt");
        //File archivo = new File("//LAPTOP-SR35DQ5L//Users//itzca//OneDrive//Documentos//ArchivosCompartidos/data.txt");
        //Scanner sc = new Scanner(archivo);
        //System.out.println("Valor: " + sc.nextLine());
        //Path From = Paths.get("//LAPTOP-SR35DQ5L//Users//itzca//OneDrive//Documentos//ArchivosCompartidos/data.txt");
        //Path To = Paths.get("C://Perfiles//PerfilesConsumo//data.txt");

        //sobreescribir el fichero de destino, si existe, y copiar
        // los atributos, incluyendo los permisos rwx
        //CopyOption[] options = new CopyOption[]{
          //StandardCopyOption.REPLACE_EXISTING,
          //StandardCopyOption.COPY_ATTRIBUTES
        //}; 
        //Files.copy(From, To, options);

        //EmailValidator validator = EmailValidator.getInstance();
        //String email = "felipecazarez1215@gmail.com";

        //if(validator.isValid(email)){
            //System.out.println("Correo Valido");
        //}else{
            //System.out.println("Correo No Valido");
        //}
 */
public class TestReadShareFolder {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String testData[] = {
                  "", 
                  "",
                  "",
                  "",
                  "",
                          ""
              };

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

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

            for(int i = 0; i < mxList.size(); i++){
                System.out.println("Correo Domain: " + mxList.get(i));
            }
        } 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;
    }

    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;
    }

    private static void say( BufferedWriter wr, String text ) throws IOException {
        wr.write( text + "\r\n" );
        wr.flush();
        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;
    }
}

Aquí está un enlace al proyecto completo en github: Proyecto en github para validar correos

10
  • 2
    Con qué código lo estás intentando hacer? La forma que yo conozco es que el servidor de destino diga que esa cuenta no existe.
    – Alfabravo
    el 22 nov. 2019 a las 21:11
  • Y que defina como "valida"? La forma de la direccion? (por ejemplo *a@acme.com.mx" ) o que la cuenta existe? El servidor existe? En fin, no hay ninguna manera para averguar por cierto en todos casos.
    – Duston
    el 22 nov. 2019 a las 22:02
  • @Alfabravo estoy desarrollando en java. el 25 nov. 2019 a las 17:39
  • @Duston para validar la forma de la dirección ahí si no tengo ningún problema eso lo puedo hacer mediante expresiones regulares, mi problema es mas que nada con determinar si existe el correo. Hasta ahorita ya tengo un ejemplo usando el mail exchange pero este funciona con varios correos excepto con hotmail, tengo dudas de esto ya que existen paginas que si te validan si el correo existe. como no se, pero si lo hacen y pues estoy interesado en eso pero hasta ahorita no eh encontrado nada mas que me ayude. el 25 nov. 2019 a las 17:41
  • Sipi, creo que RegEx es la respuesta, pero aún asi ... bueno ... éste (en inglés) discute el problema regular-expressions.info/email.html En corto, no hay ninguna manera para garantizar que una dirección es valida,
    – Duston
    el 25 nov. 2019 a las 17:54

1 respuesta 1

1

Lo que quieres no es possible (ya lo he intentado). Cada proveedor es muy diferente. La única manera es enviar un enlace de validación.

3
  • si, eso es lo que ehh estado leyendo, aunque hay paginas que si lo hacen, pero pues intentare usar una api, por ahorita y ya ver que se decide después, gracias. el 25 nov. 2019 a las 19:55
  • Y aún asi no es confiable porque algunas proveedores no emitaron ningún mensaje si el correo es válido o no.
    – Duston
    el 25 nov. 2019 a las 19:56
  • @Duston si según lo que leí también afecta si tienen activados SVFY algo así. el 25 nov. 2019 a las 22:44

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.