Javamail - 无法连接到SMTP主机

时间:2016-01-26 04:58:30

标签: java email ssl smtp

我试图从我的java发送电子邮件,但我无法连接到我的主机。 这是我的代码:

public class sendEmail implements Runnable{
     @Override
     public void run(){
        try{
            final String username = "user", password = "pass", from = "from@mail.com", to = "to@mail.com";

            Properties props = new Properties();
            props.setProperty("mail.smtp.user", username);
            props.setProperty("mail.smtp.host", "mail.host.com");
            props.setProperty("mail.smtp.ssl.enable", "true"); 
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.starttls.enable", "true");
            props.setProperty("mail.smtp.debug", "true");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);

            Message msg = new MimeMessage(session);
            try{
                msg.setSubject("Test SMTP");
                msg.setFrom(new InternetAddress(from));
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
                Transport transport = session.getTransport("smtp");
                transport.connect("mail.itbuntuksemua.com", username, password);
                transport.sendMessage(msg, msg.getAllRecipients());
                transport.close();
                System.out.println("Done");
            }catch(MessagingException | NumberFormatException | HeadlessException ex){
                ex.printStackTrace();
            }
        }catch(UnknownHostException | NumberFormatException ex){
            ex.printStackTrace();
        }
     }
 }

这里是我的SMTPAuthenticator()代码:

private class SMTPAuthenticator extends javax.mail.Authenticator {
    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        String username = "user"; 
        String password = "pass";
        return new PasswordAuthentication(username, password);
    } 
}

再次,我的报告错误:

  

DEBUG:setDebug:JavaMail 1.4.7版   DEBUG:getProvider()返回javax.mail.Provider [TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]   DEBUG SMTP:useEhlo true,useAuth true   DEBUG SMTP:尝试连接到主机" mail.host.com",端口465,isSSL true   javax.mail.MessagingException:无法连接到SMTP主机:mail.host.com,port:465;     嵌套异常是:       javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径       at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)       at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)       在javax.mail.Service.connect(Service.java:295)       在javax.mail.Service.connect(Service.java:176)       在scam.ccChecker $ sendEmail.run(ccChecker.java:186)       在java.lang.Thread.run(Thread.java:745)   引起:javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径       at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)       at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1937)       在sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)       在sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)       at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1478)       在sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:212)       在sun.security.ssl.Handshaker.processLoop(Handshaker.java:957)       在sun.security.ssl.Handshaker.process_record(Handshaker.java:892)       at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1050)       at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1363)       at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1391)       at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1375)       at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)       at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)       在com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:211)       在com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)       ......还有5个   引发者:sun.security.validator.ValidatorException:PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径       at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)       at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)       at sun.security.validator.Validator.validate(Validator.java:260)       at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)       at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)       at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)       at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1460)       ......还有16个   引起:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径       在sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)       at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)       在java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)       at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)       ......还有22个

有人能帮帮我吗? :(

2 个答案:

答案 0 :(得分:2)

您可能想尝试下载证书,使用keytool安装它,然后将它们设置为系统变量。以下是:

  1. 转到firefox浏览器中的URL,单击HTTPS证书链(URL地址旁边)。点击<!DOCTYPE html> <html> <head> <title>D3.xml Example</title> <script type="text/javascript" src="http://mbostock.github.com/d3/d3.v2.js"></script> <style type="text/css"> .chart div { font: 10px sans-serif; background-color: steelblue; text-align: right; padding: 3px; margin: 1px; color: white; display:inline-block; width:30px; } .howard { background-color: red; } </style </head> <body> <div id="chart" class="chart"> </div> <script> d3.xml("updatedphillies.xml", "application/xml", function(xml) { d3.select("#chart") .selectAll("div") .data(xml.documentElement.getElementsByTagName("doubles")) .enter().append("div") .style("height", function(d) { return d.textContent * 1 + 10 + "px"; }) .text(function(d) { return d.textContent; }); console.log(xml.documentElement.getElementsByTagName("player")); }); </script> </body> </html> 。选取名称并选择文件类型"more info" > "security" > "show certificate" > "details" > "export.."。现在你有了keystore的文件,你必须将它添加到你的JVM
  2. 找到文件example.der
  3. 使用以下内容将$JAVA_HOME/jre/lib/security/cacerts文件导入example.der文件:

    cacerts
  4. 默认密钥库密码为&#39; sudo keytool -import -alias example -keystore $JAVA_HOME/jre/lib/security/cacerts -file example.der &#39;

  5. 您可以使用显示证书指纹的此命令查看您所做的更改。

    changeit
  6. 如果这不能解决问题,请尝试将这些java选项添加为参数:

    keytool -list -keystore cacerts
    
  7. 或者您可以将它们作为系统变量放入java代码中:

    -Djavax.net.ssl.trustStore="$JAVA_HOME/jre/lib/security/cacerts"
    -Djavax.net.ssl.trustStorePassword="changeit"
    
  8. 可以在此处找到更多说明:https://stackoverflow.com/a/36427118/1696153

答案 1 :(得分:0)

也许您可以尝试设置证书,以访问SMTP端口。这样的事情:

System.setProperty("javax.net.ssl.trustStore","key");
System.setProperty("javax.net.ssl.trustStorePassword","password");