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

使用JavaMail API发送SMTP邮件遇Unsupported SSL消息异常求助

问题排查与解决方案

异常原因分析

你遇到的javax.net.ssl.SSLException: Unsupported or unrecognized SSL message异常,核心是SMTP连接配置冲突:

  • Office 365的587端口是STARTTLS端口,要求先建立普通TCP连接,再通过STARTTLS命令升级为SSL加密连接。
  • 你代码中强制指定mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory,导致JavaMail一开始就发送SSL握手请求,但服务器返回的是普通SMTP欢迎消息,SSL解析器无法识别,抛出异常。
  • 同时注释了mail.smtp.starttls.enable=true,却设置mail.smtp.starttls.required=true,配置逻辑矛盾,加剧连接失败。

修正后的代码配置

移除冲突的SocketFactory配置,开启STARTTLS支持,调整后的完整代码如下:

Properties props = new Properties();
// 代理配置(替换为真实代理地址)
props.put("mail.smtp.proxy.host", "your-proxy-host");
props.put("mail.smtp.proxy.port", "587");
// Office 365 SMTP核心配置
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.ssl.enable", "false"); // 587端口无需直接启用SSL
props.put("mail.smtp.starttls.enable", "true"); // 必须开启STARTTLS
props.put("mail.smtp.starttls.required", "true"); // 强制要求STARTTLS加密
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.ssl.protocols", "TLSv1.2"); // 指定兼容的TLS版本

// 移除以下冲突的SocketFactory配置
// props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// props.put("mail.smtp.socketFactory.port", "587");
// props.put("mail.smtp.socketFactory.fallback", "true");

Session session = Session.getInstance(props, new javax.mail.Authenticator(){
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("username@domain.com", "password");
    }
});
session.setDebug(true);

try {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("username@domain.com")); // 需与认证账号一致
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com"));
    message.setSubject("This is the email subject");
    message.setText("This is the email body");

    Transport.send(message);
    System.out.println("mailsent");
} catch (MessagingException mex) {
    mex.printStackTrace();
}

关键配置说明

  • mail.smtp.starttls.enable=true:启用STARTTLS协议,让连接先以普通TCP建立,再升级为SSL加密,适配587端口的工作机制。
  • 移除mail.smtp.socketFactory.*配置:这些配置仅适用于465端口(直接SSL连接的SMTP端口),587端口不需要。
  • 确保message.setFrom使用的邮箱与认证账号一致:Office 365要求发件人必须与SMTP认证账号匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 02:50:42