17

I am doing a sendMail Servlet with JavaMail. I have javax.mail.AuthenticationFailedException on my output. Can anyone please help me out? Thanks.

sendMailServlet code:

try {
        String host = "smtp.gmail.com";
        String from = "my@gmail.com";
        String pass = "pass";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");

        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        Address fromAddress = new InternetAddress(from);
        Address toAddress = new InternetAddress("test1@gmail.com");

        message.setFrom(fromAddress);
        message.setRecipient(Message.RecipientType.TO, toAddress);

        message.setSubject("Testing JavaMail");
        message.setText("Welcome to JavaMail");
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        message.saveChanges();
        Transport.send(message);
        transport.close();

    }catch(Exception ex){

        out.println("<html><head></head><body>");
        out.println("ERROR: " + ex);
        out.println("</body></html>");
    }

Output on GlassFish 2.1:

DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP 36sm10907668yxh.13
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587
EHLO platform-4cfaca
250-mx.google.com at your service, [203.126.159.130]
250-SIZE 35651584
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250 PIPELINING
DEBUG SMTP: Found extension "SIZE", arg "35651584"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO platform-4cfaca
250-mx.google.com at your service, [203.126.159.130]
250-SIZE 35651584
250-8BITMIME
250-AUTH LOGIN PLAIN
250-ENHANCEDSTATUSCODES
250 PIPELINING
DEBUG SMTP: Found extension "SIZE", arg "35651584"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
aWpveWNlbGVvbmdAZ21haWwuY29t
334 UGFzc3dvcmQ6
MTIzNDU2Nzhf
235 2.7.0 Accepted
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
jl.
  • 2,209
  • 12
  • 49
  • 61

6 Answers6

20

You need to implement a custom Authenticator

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;


class GMailAuthenticator extends Authenticator {
     String user;
     String pw;
     public GMailAuthenticator (String username, String password)
     {
        super();
        this.user = username;
        this.pw = password;
     }
    public PasswordAuthentication getPasswordAuthentication()
    {
       return new PasswordAuthentication(user, pw);
    }
}

Now use it in the Session

Session session = Session.getInstance(props, new GMailAuthenticator(username, password));

Also check out the JavaMail FAQ

n002213f
  • 7,805
  • 13
  • 69
  • 105
  • @n002213f : How do I use this GMAILAuthenticator when I am obtaining the session from mailservice.xml from a jndi call(jboss). – Ashwin Jun 26 '12 at 10:41
  • @Ashwin - take a look at the answer to a similar question http://stackoverflow.com/questions/3475971/configure-the-mail-service-xml-in-jboss-with-a-gmail-account – n002213f Jun 27 '12 at 07:22
  • @n002213f : you gave a brilliant solution,Now I'm implementing this just replace smtp gmail server to my own smtp server name,but getting java.lang.NoClassDefFoundError: javax/mail/Authenticator error(as I'm implementing it with the help of jsp/servlet )...any inputs.. – user1645434 Dec 03 '12 at 12:26
  • Great answer, but I prefer the second (Uma's answer). My authenticator worked, but Google's standards are (fortunately) too strict. Still, +1. – Phil C. Dec 11 '15 at 02:28
  • I am facing the exact same issue, tried this and the second answer. Neither is working for me, I am using tomcat as web container. – viveksinghggits Oct 22 '16 at 13:45
20

This error is from google security... This Can Be Resolved by Enabling Less Secure .

Go To This Link : "https://www.google.com/settings/security/lesssecureapps" and Make "TURN ON" then your application runs For Sure.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
UmaShankar
  • 221
  • 5
  • 14
  • 2
    Oh, tq :) . I have Struggled for this for so much time. This should not happen to any One . so, I made it Clean and Clear Phil C – UmaShankar Dec 14 '15 at 09:51
  • It works for me but how to make it work without having to allow less secure applications to use IMAP? – gouessej Jan 22 '16 at 10:42
2

I was missing this authenticator object argument in the below line

Session session = Session.getInstance(props, new GMailAuthenticator(username, password));

This line solved my problem now I can send mail through my Java application. Rest of the code is simple just like above.

Himanshu
  • 31,810
  • 31
  • 111
  • 133
Aaqib
  • 21
  • 1
1

When you are trying to sign in to your Google Account from your new device or application you have to unlock the CAPTCHA. To unlock the CAPTCHA go to https://www.google.com/accounts/DisplayUnlockCaptcha and then enter image description here

And also make sure to allow less secure apps on enter image description here

dasunse
  • 2,839
  • 1
  • 14
  • 32
0

The problem is, you are creating a transport object and using it's connect method to authenticate yourself. But then you use a static method to send the message which ignores authentication done by the object.

So, you should either use the sendMessage(message, message.getAllRecipients()) method on the object or use an authenticator as suggested by others to get authorize through the session.

Here's the Java Mail FAQ, you need to read.

ThePCWizard
  • 3,338
  • 2
  • 21
  • 32
0

Just wanted to share with you:
I happened to get this error after changing Digital Ocean machine (IP address). Apparently Gmail recognized it as a hacking attack. After following their directions, and approving the new IP address the code is back and running.

Zack S
  • 1,412
  • 1
  • 23
  • 37