javax. mail. Authenticationfailedexception: connection failed, no password specified?
•
Java
This program attempts to send an email but throws a runtime exception:
javax.mail.AuthenticationFailedException: Failed to connect,no password specified?
Why do I receive this exception when I provide the correct user name and password for authentication?
Both sender and recipient have g - mail accounts Both sender and recipient have g - mail accounts The sender has disabled the two-step verification process
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("mail.smtp.host","smtp.gmail.com");
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.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.port","465");
Session session = Session.getDefaultInstance( props,null);
String to = "me@gmail.com";
String from = "from@gmail.com";
String subject = "Testing...";
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
msg.setSubject(subject);
msg.setText("Working fine..!");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com",465,"username","password");
transport.send(msg);
System.out.println("fine!!");
}
catch(Exception exc) {
System.out.println(exc);
}
}
}
Even if a password is provided, I get an exception Why not certification?
Solution
Try creating a javax mail. Authenticator object and send the attribute object to the session object
Authenticator edit:
You can modify this accept user name and password, you can store them there, or where you want
public class SmtpAuthenticator extends Authenticator {
public SmtpAuthenticator() {
super();
}
@Override
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 the course you email:
SmtpAuthenticator authentication = new SmtpAuthenticator();
javax.mail.Message msg = new MimeMessage(Session
.getDefaultInstance(emailProperties,authenticator));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
