Javamail无法连接到主机

时间:2017-11-25 05:05:45

标签: java eclipse javamail

对于java web编程,我是一个新手。我试过做一个javamail代码。这是我的代码

    import java.util.Properties;..

     public class SendEmail {
     public void sendEmail(final CodeToEmailCommand emailSender) {
      try {
        Properties props = System.getProperties();

        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.ssl.trust", "*");

        Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailSender.getUsername(), emailSender.getPassword());
            }
        });

        mailSession.setDebug(true);

        Message mailMessage = new MimeMessage(mailSession);

        mailMessage.setFrom(new InternetAddress(emailSender.getFromEmail()));
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(emailSender.getToEmail()));
        mailMessage.setSubject(emailSender.getSubject());

        mailMessage.setContent(emailSender.getMessage(), "text/html");
        mailMessage.setSubject(emailSender.getSubject());
        Transport transport = mailSession.getTransport("smtp");
        transport.connect("smtp.gmail.com", emailSender.getUsername(), emailSender.getPassword());
        transport.sendMessage(mailMessage, mailMessage.getAllRecipients());

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    }
    }

但它一直给我这个例外

DEBUG: setDebug: JavaMail version 1.4.4
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.s
mtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
 PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderExc
eption: unable to find valid certification path to requested target

    ..

我尝试过改变端口。启用防火墙(在cmd中)但它仍​​然无法正常工作。 PLS。救命。我的想法已经不多了

1 个答案:

答案 0 :(得分:0)

我认为端口值应该如下

props.put("mail.smtp.port", "587");