39
votes

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)

16
Checkout biniam_Ethiopia's answer at: stackoverflow.com/questions/25341198/…biniam
@FatinAz hey how you solved this issue ,i have stuck exactly hereuser11176692
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.Juan Guillermo Alarcon

16 Answers

16
votes

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);
    }
});
82
votes

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

22
votes
11
votes

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"
8
votes

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.

5
votes

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.

4
votes

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
votes

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.

2
votes

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

    https://myaccount.google.com/u/2/lesssecureapps?pli=1&pageId=none
    
1
votes

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.
0
votes
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/

0
votes

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.

0
votes

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.

0
votes

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
-1
votes
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();
          }
    }

}