I am writing a simple javamail client to send emails from an account. I want to listen for authentication failures, so I can display an appropriate message. I am trying to use the Transport object and add a connection listener to it. I can see in the console I am getting errors but the object I am assigning to "addConnectionListener()" is not picking it up. Sample code:
mSession = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(CustomMailSender.this.mUser, CustomMailSender.this.mPassword);
}
});
mTransport = mSession.getTransport(protocol);
mTransport.addConnectionListener(new ConnectionListener() {
@Override
public void opened(ConnectionEvent e) {
Timber.e(" connection opened");
}
@Override
public void disconnected(ConnectionEvent e) {
Timber.e(" connection disconnected");
}
@Override
public void closed(ConnectionEvent e) {
Timber.e(" connection closed");
}
});
int iPort = Integer.parseInt(port);
mTransport.connect(mMailHost,iPort , user, password);
I am sending the message here
mTransport.sendMessage(message, InternetAddress.parse(recipients));
I had expected that if an attempt to connect fails, that the "disconnected" even would trigger ?
In JavaMail, "connected" really means "connected and authenticated and ready for use". If authentication fails, the Transport is never "connected".
I'm not sure why you need to "listen" for authentication failures since they'll be reported synchronously when the connect method throws AuthenticationFailedException.