Suhail Gupta Suhail Gupta - 8 months ago 784
Java Question

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

This program attempts to send e-mail but throws a run time exception:

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Why am I getting this exception when I have supplied the correct username and password for authentication?

Both the sender and receiver have g-mail accounts. The sender and the receiver both have g-mail accounts. The sender has 2-step verification process disabled.

This is the code:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

class tester {
public static void main(String args[]) {
Properties props = new Properties();
props.put("" , "");
props.put("mail.stmp.user" , "username");

//To use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.password", "password");
//To use SSL
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance( props , null);
String to = "";
String from = "";
String subject = "Testing...";
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
new InternetAddress(to));
msg.setText("Working fine..!");
Transport transport = session.getTransport("smtp");
transport.connect("" , 465 , "username", "password");
catch(Exception exc) {

Even after giving the password I get the exception. Why is it not authenticating?


Try to create an javax.mail.Authenticator Object, and send that in with the properties object to the Session object.

Authenticator edit:

You can modify this to accept a username and password and you can store them there, or where ever you want.

public class SmtpAuthenticator extends Authenticator {
public SmtpAuthenticator() {


public PasswordAuthentication getPasswordAuthentication() {
 String username = "user";
 String password = "password";
    if ((username != null) && (username.length() > 0) && (password != null) 
      && (password.length   () > 0)) {

        return new PasswordAuthentication(username, password);

    return null;

In your class where you send the email:

SmtpAuthenticator authentication = new SmtpAuthenticator();
javax.mail.Message msg = new MimeMessage(Session
                    .getDefaultInstance(emailProperties, authenticator));