Ошибка Connection reset протокол SMTP
Есть простой SMTP клиент, который лишь должен отправлять команды на сервер SMTP и получать код ответа и сообщение. Все бы ничего, но по какой-то причине дальше команды STARTTLS клиент отказывается работать с ошибкой Connection reset. В чем может быть ошибка? Привожу ниже код:
import java.net.*;
import java.io.*;
import java.util.Objects;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class EmailClient {
public static void main(String[] args) {
String host = "smtp.gmail.com";
int port = 587;
String from = "your_email@example.com";
String to = "recipient@example.com";
String subject = "Test email";
String body = "This is a test email.";
try {
// Create a socket connection to the mail server
Socket socket = new Socket(host, port);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
// Read the server's greeting
String response = in.readLine();
System.out.println(response);
// Send the EHLO command to initiate the SMTP conversation
out.println("EHLO " + host);
out.flush();
do {
response = in.readLine();
System.out.println(response);
}while (!Objects.equals(response, "250 SMTPUTF8"));
// Start a secure TLS connection
out.println("STARTTLS");
out.flush();
response = in.readLine();
System.out.println(response);
SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, host, port, true);
in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(sslSocket.getOutputStream()));
// Set the sender and recipient of the email
out.println("MAIL FROM:<" + from + ">");
out.flush();
response = in.readLine();
System.out.println(response);
out.println("RCPT TO:<" + to + ">");
out.flush();
response = in.readLine();
System.out.println(response);
// Send the email content
out.println("DATA");
out.flush();
response = in.readLine();
System.out.println(response);
out.println("Subject:" + subject);
out.println("");
out.println(body);
out.println(".");
out.flush();
response = in.readLine();
System.out.println(response);
// Close the connection
out.println("QUIT");
out.flush();
response = in.readLine();
System.out.println(response);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Источник: Stack Overflow на русском