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)

Mukit09
  • 2,956
  • 3
  • 24
  • 44
Fatin Az
  • 509
  • 2
  • 6
  • 8
  • Checkout biniam_Ethiopia's answer at: http://stackoverflow.com/questions/25341198/javax-mail-authenticationfailedexception-is-thrown-while-sending-email-in-java/33801654#33801654 – biniam Nov 19 '15 at 10:46
  • this will help someone https://stackoverflow.com/a/33801654/3514144 – Ajay Pandya Jan 13 '18 at 07:43
  • @FatinAz hey how you solved this issue ,i have stuck exactly here –  Mar 20 '19 at 11:33
  • I had the same error, unfortunately it was not enough to do what they indicate here: https://www.google.com/settings/security/lesssecureapps I had to do this: https://support.google.com/accounts/answer/185833. I also had to enable two-step verification. I hope it helps you. – Juan Guillermo Alarcon Mar 25 '20 at 18:23

18 Answers18

84

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

Raj008
  • 3,539
  • 2
  • 28
  • 26
  • 1
    I followed this article - http://examples.javacodegeeks.com/core-java/send-email-with-gmail-in-java-example/ and was getting AuthenticationFailure (gmail security) and then followed your suggestion. I am able to receive emails now. Thanks! – Jobin Thomas Oct 27 '15 at 14:39
  • This is what fixed my issue. Thanx. – PaulB Sep 06 '18 at 18:58
  • This fixed my problem. Thanks – Mukit09 Nov 24 '18 at 09:29
22
Anil Amane
  • 555
  • 7
  • 12
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);
    }
});
Ha Nguyen
  • 916
  • 6
  • 8
  • 12
    Hi I have changed the port to 587 and session code also, but still getting same error If I enable Less Secure App : https://support.google.com/accounts/answer/6010255 https://www.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 ? – Bhavana Vadodariya Oct 28 '14 at 10:46
  • 1
    @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 https://stackoverflow.com/questions/55258015/unable-to-send-email-using-servlet-and-javamail –  Mar 20 '19 at 11:32
  • @dheerajkumar I have no idea about this case, but that is Google rules, user need to set less secure when using username and password https://myaccount.google.com/lesssecureapps?pli=1. otherwise we can use google lib or OAuth2 – Ha Nguyen Mar 21 '19 at 05:43
  • @HaNguyen yup after so much of searching,i got to know that i have to use google API if want to send mails through gmail –  Mar 21 '19 at 06:17
  • How to use the same for SMTP API based authentications in JAVA ? – sskumar86 Jan 05 '21 at 10:29
12

By default Gmail account is highly secured. When we use gmail smtp from non gmail tool, email is blocked. To test in our local environment, make your gmail account less secure as

  1. Login to Gmail.
  2. Access the URL as https://www.google.com/settings/security/lesssecureapps
  3. Select "Turn on"
amitkumar
  • 176
  • 1
  • 6
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.

Saw Pyae
  • 269
  • 4
  • 9
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.

Mate Šimović
  • 945
  • 11
  • 11
4

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

Vy Do
  • 46,709
  • 59
  • 215
  • 313
4

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("conaderindicadores@gmail.com","Silueta95#");
                }
            });
    
        try {
    
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("conaderindicadores@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("netneillip@gmail.com"));
            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
    
Jorge Santos Neill
  • 1,635
  • 13
  • 6
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

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("xxxxx@gmail.com", "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.

Vino
  • 2,807
  • 1
  • 26
  • 22
1

2 possible reasons:

  • Your username may require the entire email id 'username@example.com'
  • Most obvious: The password is wrong. Debug to see if the password being used is correct.
Kedar
  • 75
  • 1
  • 6
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/

gerrytan
  • 40,313
  • 9
  • 84
  • 99
0

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.

Anil Muppalla
  • 416
  • 4
  • 14
0

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.

FCoffee
  • 116
  • 1
  • 5
0

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
karthik v
  • 1,104
  • 1
  • 14
  • 22
0

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

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.

anville95
  • 21
  • 5
-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();
          }
    }

}
  • 1
    What's that? A few code lines? Can you describe the code, the behavior, and why does it help the OP? – msrd0 Sep 09 '14 at 09:31