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 ) throws Exception {
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) {
throw new Exception(e);
}
try {
String feedback;
feedback=SR.readLine();
check(feedback);
SW.println("helo "+myComputer);
SW.flush();
feedback=SR.readLine();
check(feedback);
SW.println("mail from: "+sendAddr);
SW.flush();
feedback=SR.readLine();
check(feedback);
SW.println("rcpt to: " + rcptAddr );
SW.flush();
feedback=SR.readLine();
check(feedback);
SW.println("data");
SW.flush();
feedback=SR.readLine();
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();
check(feedback);
SW.println("quit");
SW.flush();
feedback=SR.readLine();
check(feedback);
} catch (Exception e) {
throw new Exception(e);
} finally {
try {
sock.close();
} catch (Exception e2) {
}
}
}
public static void main(String args[]) {
try {
SendMail( "localhost.bradley.edu",
"webmail.bradley.edu",
"ee-wes at bradley dot edu",
"EE-WES Student",
"olekmali at bradley dot edu",
"EE-WES Instructor",
"SMTP client in Java test",
"This is the message\n that my Java program sent."
);
System.out.println("The email was sent.");
} catch (Exception e) {
System.out.println("An error occurend sending email: "+e);
}
}
}