I tried both answers from here: Validate smtp server credentials using java without actually sending mail without correct results.
The answers work for gmail authentication, but I'd like to be able to cover any SMTP host. I am testing using smtp.1and1.com
. Whenever I give incorrect credentials (with both answers above) I still get a "success" message.
I'd like to have this formatted as the second answer, here's the code I'm using:
settings_email_test.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String server = String.valueOf(settings_email_server_inp.getText());
int port = Integer.parseInt(settings_email_port_inp.getText().toString());
String username = String.valueOf(settings_email_username_inp.getText());
String password = String.valueOf(settings_email_password_inp.getText());
boolean auth = true;
String security = "SSL";
if(confirmSMTP(server, port, username, password, auth, security)){
Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_LONG).show();
}
}
});
with this method:
public boolean confirmSMTP(String host, int port, String username, String password, boolean auth, String enctype) {
boolean result = false;
try {
Properties props = new Properties();
if (auth) {
props.setProperty("mail.smtp.auth", "true");
} else {
props.setProperty("mail.smtp.auth", "false");
}
if (enctype.endsWith("TLS")) {
props.setProperty("mail.smtp.starttls.enable", "true");
} else if (enctype.endsWith("SSL")) {
props.setProperty("mail.smtp.startssl.enable", "true");
}
Session session = Session.getInstance(props, null);
Transport transport = session.getTransport("smtp");
transport.connect(host, port, username, password);
transport.close();
result = true;
} catch(AuthenticationFailedException e) {
Toast.makeText(getApplicationContext(), "SMTP: Authentication Failed", Toast.LENGTH_LONG).show();
} catch(MessagingException e) {
Toast.makeText(getApplicationContext(), "SMTP: Messaging Exception Occurred", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMTP: Unknown Exception", Toast.LENGTH_LONG).show();
}
return result;
}
Notice: I changed the code a bit from the one in the answer, just to make the port an int and the auth a boolean to begin with. Either way, I get a success message an no error messages when I use Incorrect Credentials. Though if I were to use gmail, everything works well.
What do I need to do to make this work for any SMTP host?