我正在编写一个 Java 程序,它通过套接字接口与邮件服务器建立 TCP 连接,并发送电子邮件消息。我遇到的问题是,当我在命令行上运行它时,它会在写入“MAIL FROM:”后停止。我没有收到任何错误,它只是在那一点停止。我不知道我做错了什么,所以任何帮助将不胜感激
import java.io.*;
import java.net.*;
public class EmailSender{
public static void main(String[] args) throws Exception{
// Establish a TCP connection with the mail server.
Socket socket = new Socket("" + "hostname", 25);
// Create a BufferedReader to read a line at a time.
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// Read greeting from the server.
String response = br.readLine();
System.out.println(response);
if (!response.startsWith("220")) {
socket.close();
throw new Exception("220 reply not received from server.");
}
// Get a reference to the socket's output stream.
OutputStream os = socket.getOutputStream();
// Send HELO command and get server response.
String command = "HELO alice\r\n";
System.out.print(command);
os.write(command.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("250")) {
socket.close();
throw new Exception("250 reply not received from server.");
}
// Send MAIL FROM command.
String mailFrom = "MAIL FROM: <email>";
System.out.print(mailFrom);
os.write(mailFrom.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("250")) {
socket.close();
throw new Exception("250 reply not received from server.");
}
// Send RCPT TO command.
String commandRCPT = "RCPT TO: <email>";
System.out.print(commandRCPT);
os.write(commandRCPT.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("250")) {
socket.close();
throw new Exception("250 reply not received from server.");
}
// Send DATA command.
String commandDATA = "DATA";
System.out.print(commandDATA);
os.write(commandDATA.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("354")) {
socket.close();
throw new Exception("354 reply not received from server.");
}
// Send message data.
String msgLine1 = "email sent";
System.out.print(msgLine1);
os.write(msgLine1.getBytes("US-ASCII"));
// End with line with a single period.
String msgLine2 = ".";
System.out.print(msgLine2);
os.write(msgLine2.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("250")) {
socket.close();
throw new Exception("250 reply not received from server.");
}
// Send QUIT command.
String commandQUIT = "QUIT";
System.out.print(commandQUIT);
os.write(commandQUIT.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("221")) {
socket.close();
throw new Exception("221 reply not received from server.");
}
socket.close();
}
}