The Java Program: Email.java
1 // Email.java -- "java Email recipient [mailserver]"
2
3 import java.net.*;
4 import java.io.*;
5
6 public class Email {
7
8 final static int SMPT_Port = 25;
9
10 public static void main (String args[]) {
11 final String recipient = args[0];
12 final String host = args.length>1?args[1]:"mailhost";
13 try {
14 Email em = new Email (new Socket (host, SMPT_Port));
15 final String headers = "Subject: In the ghetto\n" +
16 "From: Elvis Presley <Elvis.Presley@jailhouse.rock>";
17 final String body = "I'm alive. Help me!";
18 em.send (recipient, host, headers, body);
19 em.close ();
20 } catch (IOException e) {
21 e.printStackTrace();
22 }
23 }
24
25 private BufferedReader in;
26 private BufferedWriter out;
27
28 Email (Socket s) throws IOException {
29 in = new BufferedReader (
30 new InputStreamReader(s.getInputStream()));
31 out= new BufferedWriter (
32 new OutputStreamWriter(s.getOutputStream()));
33 }
34
35 public void close () throws IOException {
36 out.close();
37 }
38
39 public void send (String recipient, String host, String headers,
40 String body) {
41 helo (host);
42 final String user = System.getProperty ("user.name");
43 mail (user+"@"+host);
44 rcpt (recipient);
45 data (headers, body);
46 quit ();
47 }
48
49 /*
50 HELO <SP> <domain> <CRLF>
51 In the HELO command the host sending the command identifies
52 itself; the command may be interpreted as saying "Hello, I am
53 <domain>".
54 */
55 public void helo (String host) { send ("HELO "+ host); }
56 /*
57 MAIL <SP> FROM:<reverse-path> <CRLF>
58 This command tells the SMTP-receiver that a new mail transaction
59 is starting and to reset all its state tables and buffers,
60 including any recipients or mail data. It gives the
61 reverse-path which can be used to report errors. If
62 accepted, the receiver-SMTP returns a 250 OK reply.
63 */
64 public void mail (String path) { send ("MAIL FROM: <"+path+">"); }
65 /*
66 RCPT <SP> TO:<forward-path> <CRLF>
67 This command is used to identify an individual recipient of
68 the mail data; multiple recipients are specified by multiple
69 use of this command.
70 */
71 public void rcpt (String recipient){send("RCPT TO: <"+recipient+">");}
72 public void data (String headers, String body) {
73 final String msg = headers + "\n" + body + "\n.\n";
74 send ("DATA\n"+msg);
75 }
76 public void quit () { send ("QUIT"); }
77
78 public void send (String s) {
79 try {
80 out.write (s + "\n");
81 out.flush ();
82 System.out.println (s);
83 s = in.readLine ();
84 System.out.println (s);
85 } catch (IOException e) {
86 e.printStackTrace();
87 }
88 }
89
90 }