基于 TLS 的 Java 邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13834768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Mail over TLS
提问by Surez
I am trying to send an email from my program through a TLS connection. Here is my code
我正在尝试通过 TLS 连接从我的程序发送电子邮件。这是我的代码
final String username = "XXXXXX";
final String password = "XXXXX";
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "mail.xxxx.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to_address));
message.setSubject("Test Mail");
message.setText("TestMail ");
Transport.send(message)
My email gateway has incoming Mail settings with SSL enabled and outgoing with TLS enabled on port 587. I am able to configure this settings in outlook and it's working fine. But through my java program it's saying "Connection Refused". Help Appreciated!
我的电子邮件网关具有启用 SSL 的传入邮件设置和在端口 587 上启用 TLS 的传出设置。我能够在 Outlook 中配置此设置并且它工作正常。但是通过我的 java 程序,它说“连接被拒绝”。帮助赞赏!
Worked Finally:
最后工作:
I used the InstallCertprogram to import the certicate to generate jssecacerts file and I added the file to my /jre/lib/security/ path. here is my working code
我使用InstallCert程序导入证书以生成 jssecacerts 文件,并将该文件添加到我的 /jre/lib/security/ 路径中。这是我的工作代码
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.smtp.host", "XXXXXX");
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.ssl.enable", true);
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.quitwait", "false");
properties.put("mail.smtp.auth", "true");
回答by Aviram Segal
You need to use the smtps
protocol instead of smtp
您需要使用smtps
协议而不是smtp
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.starttls.enable","true");
props.put("mail.smtps.auth", "true");
props.put("mail.smtps.host", "mail.xxxx.com");
props.put("mail.smtps.port", "587");
You can also try to set the protocol specificly for rfc822, this helps some times
您也可以尝试专门为 rfc822 设置协议,这有时会有所帮助
props.put("mail.transport.protocol.rfc822", "smtps");