Solve error javax.mail.AuthenticationFailedException
Asked Answered
M

17

44

I'm not familiar with this function to send mail in java. I'm getting an error while sending email to reset a password. Hope you can give me a solution.

Below is my code:

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

Throws the following 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)

Mensural answered 13/9, 2013 at 4:17 Comment(4)
Checkout biniam_Ethiopia's answer at: #25341698Shammer
this will help someone https://mcmap.net/q/268173/-javax-mail-authenticationfailedexception-is-thrown-while-sending-email-in-javaFortunate
@FatinAz hey how you solved this issue ,i have stuck exactly hereRainey
I had the same error, unfortunately it was not enough to do what they indicate here: google.com/settings/security/lesssecureapps I had to do this: support.google.com/accounts/answer/185833. I also had to enable two-step verification. I hope it helps you.Cornelison
I
17

You should change the port to 587, I tested your code and it's working fine

If error still happens, please change session variable to code below:

Session session = Session.getInstance(props, new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password);
    }
});
Inherent answered 13/9, 2013 at 4:48 Comment(5)
Hi I have changed the port to 587 and session code also, but still getting same error If I enable Less Secure App : support.google.com/accounts/answer/6010255 google.com/settings/security/lesssecureapps I am able to receive mail, but this is not the solution, each User wont enable this setting, how to handle this error ?Nobe
@HaNguyen hey sir i am facing the same issue, i have tried your above code but it didn't help please check out this like sir #55258515Rainey
@dheerajkumar I have no idea about this case, but that is Google rules, user need to set less secure when using username and password myaccount.google.com/lesssecureapps?pli=1. otherwise we can use google lib or OAuth2Inherent
@HaNguyen yup after so much of searching,i got to know that i have to use google API if want to send mails through gmailRainey
How to use the same for SMTP API based authentications in JAVA ?Arboreous
F
85

May be this problem cause by Gmail account protection. Just click below link and disable security settings.It will work. https://www.google.com/settings/security/lesssecureapps

Fiendish answered 4/11, 2014 at 9:13 Comment(0)
T
22
Towe answered 2/5, 2015 at 11:32 Comment(1)
That is I was searching for. I wonder why nobody mention it writing tutorials for gmail! Thank you!Justiciable
I
17

You should change the port to 587, I tested your code and it's working fine

If error still happens, please change session variable to code below:

Session session = Session.getInstance(props, new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password);
    }
});
Inherent answered 13/9, 2013 at 4:48 Comment(5)
Hi I have changed the port to 587 and session code also, but still getting same error If I enable Less Secure App : support.google.com/accounts/answer/6010255 google.com/settings/security/lesssecureapps I am able to receive mail, but this is not the solution, each User wont enable this setting, how to handle this error ?Nobe
@HaNguyen hey sir i am facing the same issue, i have tried your above code but it didn't help please check out this like sir #55258515Rainey
@dheerajkumar I have no idea about this case, but that is Google rules, user need to set less secure when using username and password myaccount.google.com/lesssecureapps?pli=1. otherwise we can use google lib or OAuth2Inherent
@HaNguyen yup after so much of searching,i got to know that i have to use google API if want to send mails through gmailRainey
How to use the same for SMTP API based authentications in JAVA ?Arboreous
D
8

Most of AuthenticationFieldException Error occur when sign-in attempted prevented, login your gmail first and go to https://www.google.com/settings/security/lesssecureapps and check turn on. I solved this kind of problem like this way.

Ditty answered 13/9, 2015 at 15:43 Comment(0)
M
5

If you are logging in to your gmail account from a new application or device, Google might be blocking that device. Try following these steps:

To protect your account, Google might make it harder to sign in to your account if we suspect it isn’t you. For example, Google might ask for additional information besides your username and password if you are traveling or if you try to sign in to your account from a new device.

Go to https://g.co/allowaccess from a different device you have previously used to access your Google account and follow the instructions. Try signing in again from the blocked app.

Myelitis answered 30/8, 2016 at 10:24 Comment(0)
S
4

Change this (set less secure app): https://www.google.com/settings/security/lesssecureapps

Slipway answered 20/6, 2016 at 9:32 Comment(0)
E
4

There are a few steps you have to keep in mind.

Now there are two scenarios If you are developing it in your local machine login to your google account in your browser, this way the google recognizes the machine.

If you have deployed the application onto a server then after the first request you will get an authentication error, so you have to give access to the server, just go here to give access- https://www.google.com/accounts/DisplayUnlockCaptcha

Empire answered 15/9, 2020 at 20:11 Comment(0)
I
3

The solution that works for me has two steps.

  1. First step

     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]","somepassword");
                 }
             });
    
         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. Enable the gmail security

     https://myaccount.google.com/u/2/lesssecureapps?pli=1&pageId=none
    
Iseabal answered 23/9, 2018 at 21:43 Comment(0)
F
2

I have been getting the same error for long time.

When i changed session debug to true

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

I got help url https://support.google.com/mail/answer/78754 from console along with javax.mail.AuthenticationFailedException.

From the steps in the link, I followed each steps. When I changed my password with mix of letters, numbers, and symbols to be my surprise the email was generated without authentication exception.

Note: My old password was more less secure.

Farmergeneral answered 17/1, 2016 at 9:36 Comment(0)
L
1

2 possible reasons:

  • Your username may require the entire email id '[email protected]'
  • Most obvious: The password is wrong. Debug to see if the password being used is correct.
Lucylud answered 18/10, 2013 at 2:3 Comment(0)
U
0
trying to connect to host "smtp.gmail.com", port 465, isSSL false

You got your gmail smtp setting wrong. Gmail requires SSL. Please see tutorials on how to send email via Java via Gmail SMTP, eg: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

Unmask answered 13/9, 2013 at 4:24 Comment(0)
Y
0

I finally did it. Google doesn't allow third party apps to sign in using your actual password (since March 30th 2022 I think). You have to create an appPassword for your app in gmail. Go to manage accounts in gmail, if you haven't allowed two step verification you'll have to, then the option for creating app password will appear. You'll just type in your app's name and tap the 'generate' button. Your password will popup and you will put it down somewhere. This is the password to be used in the Authentication anonymous class up there in the question.

Yates answered 1/2, 2023 at 18:58 Comment(0)
L
-1
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();
          }
    }

}
Lamrert answered 9/9, 2014 at 9:29 Comment(1)
What's that? A few code lines? Can you describe the code, the behavior, and why does it help the OP?Expressly
C
-1

Just in case anyone comes looking a solution for this problem.

The Authentication problems can be alleviated by activating the google 2-step verification for the account in use and creating an app specific password. I had the same problem as the OP. Enabling 2-step worked.

Caryophyllaceous answered 25/12, 2015 at 20:12 Comment(0)
N
-1

I had this issue as well but the solution had nothing to do with coding. Make sure you are able to connect to gmail. Ping smtp.gmail.com. If you don't get a reply check your firewall settings. It could also be a proxy setting issue.

Nitramine answered 12/9, 2016 at 19:9 Comment(0)
G
-1

Implement Three things with given SMTP settings

  1. Disable two factor aunthentication: https://myaccount.google.com/security
  2. Allow less secure apps : https://www.google.com/settings/security/lesssecureapps
  3. Allow new devices using the link: https://g.co/allowaccess

SMTP Settings:

  • smtp.gmail.com
  • Port: 465
  • Use SSL
  • From Email Address
  • Gmail Username
  • Gmail Password
  • Recepient Email Address
Goingover answered 25/6, 2021 at 5:23 Comment(0)
S
-1

This is because our application cant bypass 2-step verification. If you are using Gmail then here's a solution. Click Manage your google account

Go to "Manage your Google Account"

Click Security Menu item

Go into Security Tab and enable 2-Step verification if not already enabled.

Navigate to App passwords

Select a name and generate the password. Copy the 16 letter password before you close the next window. Select Other

Sericin answered 1/9, 2022 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.