JavaMail mail.smtp.ssl.enable is not working

11 java ssl jakarta-mail

I read on several sites that, when using the JavaMail API, to set the property mail.smtp.ssl.enable to true. I have some code as follows:

props.put("mail.smtp.host", "exchangemail1.example.com");
props.put("mail.from", "myemail@example.com");
props.put("mail.smtp.starttls.enable", "true");
// I tried this by itself and also together with ssl.enable)
props.put("mail.smtp.ssl.enable", "true");

Session session = Session.getInstance(props, null);
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, "me.at@example.com");  
    // also tried @gmail.com
msg.setSubject("JavaMail ssl test");
msg.setSentDate(new Date());
msg.setText("Hello, world!\n");
props.put("mail.smtp.auth", "false");

Transport trnsport;
trnsport = session.getTransport("smtp");
trnsport.connect();
msg.saveChanges(); 
trnsport.sendMessage(msg, msg.getAllRecipients());
trnsport.close();
Run Code Online (Sandbox Code Playgroud)

This sends email, but:

  1. when I do traffic capture, I see it is not encrypted
  2. When using debug (props.put("mail.debug", "true")), I see that "isSSL false"

(我也在上面尝试添加props.put("mail.smtp.auth","true")+用户/密码....)

我有什么想法我做错了吗?

小智 15

要使用SSL,您应该通过更改将协议从SMTP更改为SMTPS

trnsport = session.getTransport("smtp");
Run Code Online (Sandbox Code Playgroud)

trnsport = session.getTransport("smtps");
Run Code Online (Sandbox Code Playgroud)


Ral*_*lph 7

形成Java Doc:

请注意,如果您使用"smtps"协议访问SMTP over SSL,则所有属性都将命名为"mail.smtps.*".


Boz*_*zho 3

我建议使用 Apache commons-email。它具有最常用属性(包括 SSL / TLS)的设置器,并且使用起来更加友好,并且位于 JavaMail API 之上。

更新:我正在查看公共电子邮件代码,并看到这些行:

properties.setProperty("mail.smtp.starttls.enable", this.tls);
properties.setProperty("mail.smtp.auth", "true");
Run Code Online (Sandbox Code Playgroud)

所以,也尝试一下这些属性。