import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Test {
private static void check(String reply) throws Exception {
if (reply.startsWith("2")||reply.startsWith("3")) return;
throw new Exception(reply);
}
public static void SendMail(String myComputer, String smtpServer,
String sendAddr, String sendName,
String rcptAddr, String rcptName,
String emSubject, String emBody ) {
Socket sock=null;
BufferedReader SR=null;
PrintWriter SW=null;
try {
sock = new Socket(smtpServer, 25);
SR=new BufferedReader(new InputStreamReader(sock.getInputStream()));
SW=new PrintWriter (sock.getOutputStream());
} catch (Exception e) {
System.out.println("ERROR while connecting to the server: "+e);
return;
}
try {
String feedback;
SW.println("helo "+myComputer);
SW.flush();
feedback=SR.readLine();
System.out.println(feedback);
check(feedback);
SW.println("mail from: "+sendAddr);
SW.flush();
feedback=SR.readLine();
System.out.println(feedback);
check(feedback);
SW.println("rcpt to: " + rcptAddr );
SW.flush();
feedback=SR.readLine();
System.out.println(feedback);
check(feedback);
SW.println("data");
SW.flush();
feedback=SR.readLine();
System.out.println(feedback);
check(feedback);
SW.println("From: " +sendName+" <"+sendAddr+">");
SW.println("To: " +rcptName+" <"+rcptAddr+">");
SW.println("Subject: " +emSubject);
SW.println();
SW.println(emBody);
SW.println(".");
SW.flush();
feedback=SR.readLine();
System.out.println(feedback);
check(feedback);
SW.println("quit");
SW.flush();
feedback=SR.readLine();
System.out.println(feedback);
check(feedback);
System.out.println("Email sent.");
} catch (Exception e) {
System.out.println("ERROR while sending email: "+e);
return;
} finally {
try {
sock.close();
} catch (Exception e2) {
}
}
}
public static void main(String args[]) {
SendMail( "localhost.bradley.edu",
"cegt201.bradley.edu",
"ee-web at bradley dot edu",
"EE-WEB Student",
"olekmali at bradley dot edu",
"EE-WEB Instructor",
"SMTP client in Java test",
"This is the message\n that my Java program sent."
);
}
}