【发布时间】:2016-05-21 02:27:22
【问题描述】:
我从这里尝试了两个答案:Validate smtp server credentials using java without actually sending mail,但没有正确的结果。
答案适用于 gmail 身份验证,但我希望能够覆盖任何 SMTP 主机。我正在使用smtp.1and1.com 进行测试。每当我提供不正确的凭据(以上两个答案)我仍然会收到“成功”消息。
我想将此格式化为第二个答案,这是我正在使用的代码:
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();
}
}
});
用这个方法:
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;
}
注意:我对答案中的代码进行了一些更改,只是为了使端口为 int,而 auth 为布尔值。无论哪种方式,当我使用 Incorrect Credentials 时,我都会收到成功消息和无错误消息。虽然如果我使用 gmail,一切都很好。
我需要做什么才能使任何 SMTP 主机都能正常工作?
【问题讨论】: