Question: Is there any other way to verify credentials before sending an email while using Java Mail API?
Introduction:
My goal is to brake down sending emails into 2 steps:
Sign in (if username or password doesn't match, a user will get the corresponding message)
Send email
Currently I'm achieving it from this snippet of code:
...
// no Authenticator implementation as a parameter
Session session = Session.getInstance(Properties props);
Transport transport = session.getTransport("smtp");
transport.connect(username, password);
transport.sendMessage(Message msg, Address[] addresses);
...
Conclusion: I'm getting my work done just fine, but I'm curious if there are any other ways to achieve the same goal?
This approach is more convenient than my first one for two reasons:
send(Message msg)
, which we couldn’t use earlierThis time we need to pass Authenticator in getInstance()
method
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(“username”, “password”);
}
}
/*
* no need to pass protocol to getTransport()
* no need to pass username and password to connect()
* if credentials were incorrect, you would get a corresponding error
*/
session.getTransport().connect();
// no need to use instance, we simply use static method
Transport.send(message);