【发布时间】:2019-05-26 12:19:13
【问题描述】:
我正在尝试检查是否为使用 JavaMail 库的电子邮件帐户正确输入了 SMTP 设置/凭据。我遇到的问题是无论凭据有效还是无效,连接都是成功的。
这是在启用了第 3 部分应用程序访问的 GMail 帐户上进行测试的,并且可以通过 JavaMail 中包含的 IMAP 和 GIMAP 提供程序连接到该帐户。如果 SMTP 设置正确,那么它也可以发送邮件,我只是尝试添加一个层,以便在您配置新帐户时,测试 SMTP 凭据和设置以验证配置是否正确。
这里的大图是这个代码所属的项目不会只用于GMail帐户,它应该支持任何IMAP/SMTP电子邮件服务。
我在创建会话和传输时尝试了多种变体,主要遵循相关问题中的示例答案:
Javamail transport getting success to authenticate with invalid credentials
Validate smtp server credentials using java without actually sending mail
这些答案似乎对我不起作用,因为问题是传输正在使用无效凭据成功连接,尝试发送消息确实会失败,但会出现不是 AuthenticationFailedException 实例的 MessagingException。 . 这两个相关问题中的第二个,多个 cmets 声称有类似的问题,但没有提供解决方案。
// For the purposes of this code snippet getSmtpUsername() and getSmtpPassword() return a constant string value representing the username and password to be used when logging into SMTP server.
public Authenticator getSMTPAuthenticator() {
return new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( getSmtpUsername(), getSmtpPassword() );
}
};
}
public boolean authenticateSMTP( SMTPConfiguration smtpConfiguration ) throws MessagingException {
try {
Properties properties = new Properties( );
properties.put( "mail.smtp.auth", true );
properties.put( "mail.smtp.host", "smtp.gmail.com" );
properties.put( "mail.smtp.port", 465 );
properties.put( "mail.smtp.socketFactory.port", 465);
properties.put( "mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory" );
Transport transport = Session.getInstance( properties, getSMTPAuthenticator() ).getTransport("smtp"); //.getTransport() also has not solved this issue
transport.connect( "smtp.gmail.com", 465, getSmtpUsername(), getSmtpPassword() );
transport.close();
return true;
} catch ( AuthenticationFailedException e ) { //TODO: this exception just never happens even with wrong credentials...
return false;
}
}
我的预期结果是,如果 getSmtpUsername() 或 getSmtpPassword() 返回的字符串值与有效帐户不一致,则将抛出 AuthenticationFailedException,或者实施其他方法来确定凭据是否不正确.
【问题讨论】:
-
修复所有这些common JavaMail mistakes,然后发布JavaMail debug output。
-
@BillShannon 我已经进行了建议的更改并找出了问题所在。非常感谢!
标签: java email authentication smtp jakarta-mail