TLS上的Java Mail

时间:2012-12-12 07:21:48

标签: java email ssl

我正在尝试通过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("from@xxxx.com"));
    message.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse(to_address));
    message.setSubject("Test Mail"); 
    message.setText("TestMail ");
    Transport.send(message)

我的电子邮件网关具有启用了SSL的传入邮件设置,并在端口587上启用了TLS传出。我可以在Outlook中配置此设置并且它正常工作。但通过我的java程序,它说“拒绝连接”。 帮助感谢!

最后工作:

我使用InstallCert程序导入certicate以生成jssecacerts文件,并将文件添加到my / jre / lib / security / path。这是我的工作代码

    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"); 

1 个答案:

答案 0 :(得分:4)

您需要使用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");

你也可以尝试特别为rfc822设置协议,这有时会有所帮助

props.put("mail.transport.protocol.rfc822", "smtps");