使用JakartaMail通过Gmail SMTP发送邮件失败:无法连接主机
使用Gmail SMTP端口和JakartaMail发送邮件时连接失败问题
问题详情
使用Gmail SMTP服务和JakartaMail发送邮件时,出现连接失败错误,无法连接到smtp.gmail.com的465端口,响应码为-1。
相关代码
final String email = "xxxx@xxx.com"; final String pass = "xxxxx"; public Email() { this.callerObj = this; this.msg = null; this.mp = null; this.props = null; this.session = null; this.props = new Properties(); this.props.setProperty("mail.smtp.auth", "true"); this.props.setProperty("mail.smtp.starttls.enable", "true"); this.props.setProperty("mail.smtp.host", "smtp.gmail.com"); this.props.setProperty("mail.smtp.port", "465"); this.props.setProperty("mail.debug", rbApp.getString("app.mail.debug")); this.session = Session.getInstance(this.props, null); } // ... 其他代码 ... session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(email, pass); } }); // ... 其他代码 ...
错误信息
MessagingException caught >> Fail to send Email >> Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
Thunderbird中的SMTP配置
- SMTP服务器:smtp.gmail.com
- 端口:465
- 连接安全:SSL/TLS
- 认证方式:正常密码
解决方案
1. 修正协议属性配置
端口465对应SSL加密的SMTP协议,代码中应使用mail.smtps.*前缀的属性,而非mail.smtp.*,同时无需开启STARTTLS(STARTTLS是587端口的明文升级加密方式)。修改后的配置如下:
this.props = new Properties(); this.props.setProperty("mail.smtps.auth", "true"); this.props.setProperty("mail.smtps.host", "smtp.gmail.com"); this.props.setProperty("mail.smtps.port", "465"); this.props.setProperty("mail.debug", rbApp.getString("app.mail.debug"));
2. 检查Gmail账号权限
- 若账号未开启两步验证:需开启不太安全的应用访问(注:Google已逐步淘汰该选项,优先推荐使用应用专用密码)。
- 若账号开启了两步验证:必须使用应用专用密码替代原账号密码进行认证。
3. 排查网络限制
检查本地防火墙、公司/校园代理是否拦截了465端口的出站连接,必要时临时关闭防火墙测试。
4. 切换到587端口
若465端口始终无法连接,可尝试使用587端口(STARTTLS加密),配置如下:
this.props = new Properties(); this.props.setProperty("mail.smtp.auth", "true"); this.props.setProperty("mail.smtp.starttls.enable", "true"); this.props.setProperty("mail.smtp.host", "smtp.gmail.com"); this.props.setProperty("mail.smtp.port", "587"); this.props.setProperty("mail.debug", rbApp.getString("app.mail.debug"));
内容的提问来源于stack exchange,提问作者imzz
相关产品推荐
相关产品推荐

