Отправка электронной почты на Java не работает при переключении компьютеров?

1

Я нашел базу этого кода в другом потоке stackoverflow (обязательно укажу для моего проекта, но оставил URL-адрес в школе) и получил код для работы на компьютере школы (с использованием порта 587), однако, когда я пытаюсь сделать то же самое кода дома на одном и том же программном обеспечении (JCreator), программа больше не работает и дает эту ошибку:

<pre> <code> 
--------------------Configuration: <Default>--------------------
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at SendEmail.<init>(SendEmail.java:86)
    at SendEmail.main(SendEmail.java:93)
Caused by: javax.mail.MessagingException: Could not convert socket to TLS;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1907)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at SendEmail.<init>(SendEmail.java:78)
    ... 1 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:486)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1902)
    ... 8 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
    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:326)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
    ... 18 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
    ... 24 more

Process completed.
</code>  </pre> 

Если это проще, это код. Первоначально код пришел в один огромный основной метод, но я попытался изменить его так, что есть метод (не работал), поэтому я создал один огромный конструктор... это нормально? Кроме того, он использует API Java

<pre> <code> 

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.swing.*;
import java.util.*;
import java.io.*;

/**
SendEmail Class
By: Jana Dbouk
June 06, 2014
ICS 4U0 - Mr. Campos

SendEmail Class Functions:
        * Volunteer student enters custom email message
        * Program sends email to Mr. Makridis
        * Self Testing Main Method

 */

public class SendEmail
{

    public SendEmail ()
    {

final String username = "[email protected]";
 final String password = "sugarcakes"; 
    String host = "smtp.gmail.com";


        // Connects to the email host
        Properties emailProperties = new Properties ();
         emailProperties .put("mail.smtp.starttls.enable", "true");
        emailProperties.put("mail.smtp.host", host);
        emailProperties.put("mail.smtp.user", username);
         emailProperties.put("mail.smtp.password", password);
        emailProperties.put("mail.smtp.port", "587");
         emailProperties .put("mail.smtp.auth", "true");


        // Checks to see if student volunteer email/password are correct
       Session session = Session.getInstance (emailProperties,
                new javax.mail.Authenticator ()
        {
            protected PasswordAuthentication getPasswordAuthentication ()
            {
                return new PasswordAuthentication (username, password);
            }
        }
        );

        // Send a email to the teacher

        try
        {

            Message emailToTeacher = new MimeMessage (session);

            // Volunteer student email
            emailToTeacher.setFrom (new InternetAddress ("[email protected]"));

            // Teacher email
            emailToTeacher.setRecipients (Message.RecipientType.TO,
                    InternetAddress.parse ("[email protected]"));

            // Subject Title
            emailToTeacher.setSubject ("New Email from Breakfast Club");

            // Text within email
            String emailMessage = JOptionPane.showInputDialog ("Enter the email message.");
            emailToTeacher.setText (emailMessage);

            // Sends emailToTeacher to teacher
            Transport.send (emailToTeacher);

            // Let the student know the emailToTeacher has been sent
            JOptionPane.showMessageDialog (null, "Email successfully sent to Mr. Makridis.");

        }
        catch (MessagingException e)
        {
            throw new RuntimeException (e); // Error message

        }

    }     // Self testing main method
    public static void main (String[] args)
    {
        new SendEmail ();
    }
} </code>  </pre> 
  • 0
    Какая строка в вашей программе, по словам трассировки, начала проблему?
Теги:
javamail
port

1 ответ

2
Лучший ответ

Это ошибка сертификата, а не ошибка кода.

Я написал сообщение в блоге об этом пару лет назад:

http://springinpractice.com/2012/04/29/fixing-pkix-path-building-issues-when-using-javamail-and-smtp/

Ещё вопросы

Сообщество Overcoder
Наверх
Меню