将 JavaMail 与 TLS 一起使用
我在 SO 上发现了其他几个关于 JavaMail API 和通过 SMTP 服务器发送邮件的问题,但没有一个讨论过使用 TLS 安全性.我正在尝试使用 JavaMail 通过我的工作 SMTP 邮件服务器向自己发送状态更新,但它需要 TLS,而且我在网上找不到任何关于如何使用 JavaMail 访问需要 TLS 加密的 SMTP 服务器的示例.有人可以帮忙吗?
I found several other questions on SO regarding the JavaMail API and sending mail through an SMTP server, but none of them discussed using TLS security. I'm trying to use JavaMail to send status updates to myself through my work SMTP mail server, but it requires TLS, and I can't find any examples online of how to use JavaMail to access an SMTP server that requires TLS encryption. Can anyone help with this?
推荐答案
我们的产品中实际上有一些通知代码,它使用 TLS 发送邮件(如果可用).
We actually have some notification code in our product that uses TLS to send mail if it is available.
您需要设置 Java Mail 属性.您只需要 TLS,但如果您的 SMTP 服务器使用 SSL,则可能需要 SSL.
You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.
Properties props = new Properties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true"); // If you need to authenticate
// Use the following if you need SSL
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
然后您可以将其传递给 JavaMail 会话或任何其他会话实例化器,例如 Session.getDefaultInstance(props)
.
You can then either pass this to a JavaMail Session or any other session instantiator like Session.getDefaultInstance(props)
.
相关文章