Resuelve el error javax.correo.Excepción de autenticación fallida


No estoy familiarizado con esta función para enviar correo en java. Recibo un error al enviar un correo electrónico para restablecer la contraseña. Espero que puedas darme una solución.

A continuación está mi código:

public synchronized static boolean sendMailAdvance(String emailTo, String subject, String body)
{
String host = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-ADDRESS");
String userName = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-USERNAME");
String password = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-PASSWORD");
String port = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-PORT");
String starttls = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-STARTTLS");
String socketFactoryClass = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-SOCKET-CLASS");
String fallback = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-ALLOW-FALLBACK");                         

        try
        {
            java.util.Properties props = null;
            props = System.getProperties();
            props.put("mail.smtp.user", userName);
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.debug", "true");

            if(!"".equals(port))
            {
                props.put("mail.smtp.port", port);
                props.put("mail.smtp.socketFactory.port", port);
            }

            if(!"".equals(starttls))
                props.put("mail.smtp.starttls.enable",starttls);

            if(!"".equals(socketFactoryClass))
                props.put("mail.smtp.socketFactory.class",socketFactoryClass);

            if(!"".equals(fallback))
                props.put("mail.smtp.socketFactory.fallback", fallback);

            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(userName));
            msg.setSubject(subject);                
            msg.setText(body, "ISO-8859-1");
            msg.setSentDate(new Date());
            msg.setHeader("content-Type", "text/html;charset=\"ISO-8859-1\"");
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));
            msg.saveChanges();

            Transport transport = session.getTransport("smtp");
            transport.connect(host, userName, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

            return true;
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
            return false;
        }
}

Lanza el siguiente error:

DEBUG: setDebug: JavaMail version 1.4.1ea-SNAPSHOT
DEBUG: getProvider() returning   javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false 220 mx.google.com ESMTP m4sm5929870pbg.38 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 465
EHLO fatin
250-mx.google.com at your service, [175.139.198.14]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN
250-ENHANCEDSTATUSCODES
250 CHUNKING
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
YWNjb3VudEBibG9vbWluZy5jb20ubXk=
334 UGFzc3dvcmQ6
Ymxvb21pbmc=
535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 m4sm5929870pbg.38 - gsmtp
[STDOUT] javax.mail.AuthenticationFailedException
[STDOUT] at javax.mail.Service.connect(Service.java:319)
[STDOUT] at javax.mail.Service.connect(Service.java:169)
[STDOUT] at com.vlee.util.mail.SendMail.sendMailAdvance(SendMail.java:283)
[STDOUT] at com.vlee.servlet.ecommerce.DoMemberLogin.fnSendPwd(DoMemberLogin.java:251)
[STDOUT] at com.vlee.servlet.ecommerce.DoMemberLogin.doPost(DoMemberLogin.java:72)
Author: Bilesh Ganguly, 2013-09-13

14 answers

Debe cambiar el puerto a 587, he probado su código y está funcionando bien

Si el error sigue ocurriendo, cambie la variable de sesión al código siguiente:

Session session = Session.getInstance(props, new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password);
    }
});
 12
Author: Ha Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-13 04:48:00

Puede ser este problema causado por la protección de la cuenta de Gmail. Simplemente haga clic en el enlace de abajo y desactivar la seguridad settings.It funcionará. https://www.google.com/settings/security/lesssecureapps

 69
Author: Raj008,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-04 09:13:36
 17
Author: Anil Amane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-02 11:32:05

La mayor parte del error AuthenticationFieldException se produce cuando se intenta impedir el inicio de sesión, inicie sesión en gmail primero y vaya a https://www.google.com/settings/security/lesssecureapps y comprobar activar. Resolví este tipo de problema de esta manera.

 7
Author: sawpyae,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-13 15:43:04

Por defecto la cuenta de Gmail es altamente segura. Cuando utilizamos gmail smtp desde la herramienta no gmail, el correo electrónico se bloquea. Para probar en nuestro entorno local, haga que su cuenta de gmail sea menos segura como

  1. Inicie sesión en Gmail.
  2. Accede a la URL como https://www.google.com/settings/security/lesssecureapps
  3. Seleccione "Activar"
 7
Author: amitkumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-10 10:15:58

Cambiar esto (establecer aplicación menos segura): https://www.google.com/settings/security/lesssecureapps

 3
Author: Do Nhu Vy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-20 09:32:17

Si inicias sesión en tu cuenta de gmail desde una nueva aplicación o dispositivo, es posible que Google esté bloqueando ese dispositivo. Intenta seguir estos pasos:

Para proteger tu cuenta, Google podría dificultar el inicio de sesión en tu cuenta si sospechamos que no eres tú. Por ejemplo, Google podría solicitar información adicional además de su nombre de usuario y contraseña si viaja o si intenta iniciar sesión en su cuenta desde un dispositivo nuevo.

Ir a https://g.co/allowaccess de un dispositivo diferente que haya utilizado anteriormente para acceder a su cuenta de Google y seguir las instrucciones. Intenta iniciar sesión de nuevo desde la aplicación bloqueada.

 3
Author: Mate Šimović,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-30 10:24:59

He estado recibiendo el mismo error durante mucho tiempo.

Cuando cambié depuración de sesión a verdadero

Session session = Session.getDefaultInstance(props, new GMailAuthenticator("[email protected]", "xxxxx"));
session.setDebug(true);

Tengo url de ayuda https://support.google.com/mail/answer/78754 desde la consola junto con javax.correo.Excepción de autenticación fallida.

De los pasos en el enlace, seguí cada paso. Cuando cambié mi contraseña con una mezcla de letras, números y símbolos para ser mi sorpresa, el correo electrónico se generó sin excepción de autenticación.

Nota: Mi viejo la contraseña era menos segura.

 2
Author: Vino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-17 09:36:51

2 posibles razones:

  • Su nombre de usuario puede requerir el id de correo electrónico completo '[email protected]"
  • Lo más obvio: La contraseña es incorrecta. Debug para ver si la contraseña es correcta.
 1
Author: Kedar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-18 02:03:16
trying to connect to host "smtp.gmail.com", port 465, isSSL false

Tienes mal la configuración de gmail smtp. Gmail requiere SSL. Por favor, vea tutoriales sobre cómo enviar correo electrónico a través de Java a través de Gmail SMTP, por ejemplo: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example /

 0
Author: gerrytan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-13 04:24:33
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendMail1 {

    public static void main(String[] args) {
        // Recipient's email ID needs to be mentioned.
          String to = "valid email to address";

          // Sender's email ID needs to be mentioned
          String from = "valid email from address";


          // Get system properties
          Properties properties = System.getProperties();

          properties.put("mail.smtp.starttls.enable", "true"); 
          properties.put("mail.smtp.host", "smtp.gmail.com");

          properties.put("mail.smtp.port", "587");
          properties.put("mail.smtp.auth", "true");
          Authenticator authenticator = new Authenticator () {
                public PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication("userid","password");//userid and password for "from" email address 
                }
            };

            Session session = Session.getDefaultInstance( properties , authenticator);  
          try{
             // Create a default MimeMessage object.
             MimeMessage message = new MimeMessage(session);

             // Set From: header field of the header.
             message.setFrom(new InternetAddress(from));

             // Set To: header field of the header.
             message.addRecipient(Message.RecipientType.TO,
                                      new InternetAddress(to));

             // Set Subject: header field
             message.setSubject("This is the Subject Line!");

             // Now set the actual message
             message.setText("This is actual message");

             // Send message
             Transport.send(message);
             System.out.println("Sent message successfully....");
          }catch (MessagingException mex) {
             mex.printStackTrace();
          }
    }

}
 0
Author: Pana Emp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-09 09:29:55

En caso de que alguien venga buscando una solución para este problema.

Los problemas de autenticación se pueden aliviar activando la verificación de 2 pasos de Google para la cuenta en uso y creando una contraseña específica de la aplicación. Tuve el mismo problema que la OP. Habilitar 2 pasos funcionó.

 0
Author: Anil Muppalla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-25 20:12:36

También tuve este problema, pero la solución no tenía nada que ver con la codificación. Asegúrate de poder conectarte a gmail. Ping smtp.gmail.com. Si no recibe una respuesta, compruebe la configuración del firewall. También podría ser un problema de configuración de proxy.

 0
Author: FCoffee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-12 19:09:54

La solución que funciona para mí tiene dos pasos.

  1. Primer paso

    package com.student.mail;
    
    import java.util.Properties;
    
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    /**
     *
     * @author jorge santos
     */
    public class GoogleMail {
        public static void main(String[] args) {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465"); 
            Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("[email protected]","Silueta95#");
                }
            });
    
        try {
    
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Test Mail");
    
            Transport.send(message);
    
            System.out.println("Done");
    
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    
    }
    
  2. Habilitar la seguridad de gmail

    https://myaccount.google.com/u/2/lesssecureapps?pli=1&pageId=none
    
 0
Author: Jorge Santos Neill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-23 21:43:12