You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaMail API发邮件遇类型不兼容错误:需Void却得PasswordAuthentication

解决JavaMail API中“类型不兼容:找到'javax.mail.PasswordAuthentication',所需'java.lang.Void'”错误

你的代码存在语法错误,创建Authenticator匿名内部类时,错误提前闭合了new javax.mail.Authenticator()的括号,导致编译器把后续代码块当成Session.getDefaultInstance方法调用后的额外代码,而非Authenticator的子类实现,进而误解了getPasswordAuthentication方法的返回值类型。

修正后的代码如下:

session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(Util.EMAIL, Util.PASSWORD);
    }
});

return null;
}

修正说明

  • 移除new javax.mail.Authenticator()后多余的右括号),让匿名内部类的大括号{紧跟在Authenticator()之后,确保代码块属于Authenticator子类的实现逻辑。
  • 修正后getPasswordAuthentication方法能正确重写父类的同名方法,返回类型与PasswordAuthentication匹配,不会再出现返回值类型不兼容的错误。

内容的提问来源于stack exchange,提问作者Khaled

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:15:46