我尝试了这里的两个答案: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 设为 boolean 值。无论哪种方式,当我使用不正确的凭据时,我都会收到成功消息,并且没有错误消息。不过如果我使用 gmail,一切都会正常。
我需要做什么才能使其适用于任何 SMTP 主机?
最佳答案
我发布的链接中给出的答案都有效 - 我的问题是我的应用程序正在缓存信息,并且我首先使用正确凭据运行了“测试”。由于这些凭据是肯定的并且应用程序缓存了这些凭据,因此它不断写入成功。
我在销毁应用程序时清除了缓存,并且这些凭据也随之清除。我现在能够获得正确的交互。
关于java - Android 验证电子邮件凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35320242/