Unsupported or unrecognized ssl-message exception at startHandshake after issuing STARTTLS command in a java program

后端 未结 1 1064
情歌与酒
情歌与酒 2021-01-17 05:35

I have written a simple e-mail client in java without using the JavaMail API, as by what I read from the documentation it seems necessary to split the messages up into head

1条回答
  •  無奈伤痛
    2021-01-17 06:19

    To be clear, the main intention behind this answer is to mark the question as answered, because actually the solution is found in the comments to the question. The problem lies in the readInputRun() that reads part of the ServerHello, so letting the reading thread interrupt itself before the handshake and restarting it after it solves it:

    dos.write("STARTTLS\r\n".getBytes());
    
    SSLSocket sslSocket = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(socket, "mail.arcor.de", 587, true);
    dos = new DataOutputStream(sslSocket.getOutputStream());
    dis = new DataInputStream(sslSocket.getInputStream());
    
    sslSocket.startHandshake();
    
    new Thread(() -> {readInputRun();}).start();
    
    dos.write(("EHLO " + InetAddress.getLocalHost().getHostAddress() + "\r\n").getBytes());
    
    dos.write("QUIT\r\n".getBytes());
    

    and:

    private static void readInputRun() {
        try {
            int input;
            String allInput = "";
            while((input = dis.read()) >= 0) {
                allInput += (char) input;
                System.out.print(allInput.charAt(allInput.length() - 1));
    
                if(allInput.endsWith("Start TLS\r\n")) {
                    break;
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    

    0 讨论(0)
提交回复
热议问题