我需要发送一个电子邮件使用Javamail和TLS (不是STARTTLS,但一个专用的smtp端口只为SSL/TLS!)。我只找到了gmail的例子,但是使用了STARTTLS。有没有人能贴出一个普通的SSL/TLS的例子?非常感谢!
发布于 2012-08-26 23:00:23
official examples for JavaMail with Gmail使用SMTP (即专用端口上SSL/TLS上的SMTP),而不是STARTTLS。本质上,使用JavaMail的属性应该是mail.smtps.*而不是mail.smtp.*。
如果您想强制使用特定版本的SSL/TLS,例如TLSv1.0,您将需要创建自己的SSLSocketFactory,可能会包装默认的SSLSocketFactory (或任何其他您需要定制的内容),但在返回套接字之前,您需要调用sslSocket.setEnabledProtocols(new String[] { "TLSv1" })。
您需要通过mail.smtps.ssl.socketFactory配置属性将该SSLSocketFactory作为实例传递,或者通过mail.smtps.ssl.socketFactory.class作为完全限定的类名传递(在本例中,您的类必须实现一个名为getDefault的静态方法)。
为了防止MITM攻击,您还需要让客户机验证服务器主机名:您需要将mail.smtps.ssl.checkserveridentity设置为true,因为它在缺省情况下似乎是false。
发布于 2012-08-27 03:02:24
对于记录,基于Brunos的答案:
private static void sendMailSSL(String host, int port, String user, String pass, String to, String from, String subj, String message) throws UnsupportedEncodingException, MessagingException
{
Properties props = System.getProperties();
props.put("mail.smtps.ssl.checkserveridentity", true);
Session session = Session.getDefaultInstance(props, null);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from, from));
msg.addRecipients(RecipientType.TO, to);
msg.setSubject(subj);
msg.setText(message);
Transport t = session.getTransport("smtps");
try {
t.connect(host, port, user, pass);
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}
}请注意,我并没有测试是否真的考虑了checkserveridentity。至少它真的使用了SSL :-)
https://stackoverflow.com/questions/12130200
复制相似问题