ソケット インターフェイスを介してメール サーバーとの TCP 接続を確立し、電子メール メッセージを送信する Java プログラムを作成しています。私が抱えている問題は、コマンドラインで実行すると、「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();
}
}