Command Line EMailer            Peter Komisar


/*
Van der Linden in 'Just Java' has an email reader class that uses the method readLine which is
deprecated in DataInputStream. On the other hand it isn't deprecated in BufferedReader. If we
convert the read from a stream of bytes to a stream of chars, we can use BufferedReader and
then use it's undeprecated version of readLine( ).  I added some code so you could enter a user
and a host machine from the command line. I also added some code based on System.in.read( )
that allows inputing a message. Note you have to hard code the sender mail address in to use
this code to mail on the net. It isn't pretty but it does work.
*/

import java.io.*;
import java.net.*;

public class Emailer{
public static void main(String args[]) throws IOException{
    int ascii=0;
    String message="\n";
    Socket sock;
    DataInputStream dis;
    PrintStream ps;
    InputStreamReader isr;
    BufferedReader bis;

if(args.length == 0 ){        // signal the user to enter a recipient and machine address
    System.out.println
    ("Enter the e recipient followed by the host \n" +
     "Domain name or IP address");
    System.exit(0);
   }

System.out.println("Enter the message. Signal the end by entering\n" +
"a period on one line followed by Control-Z in Dos or Control-Z in " + "Unix");
// Putting a period on it's own line here prevents a ? mark appearing at the end of your message
 

// here is where we read in the message
try{
    while(ascii!=-1){
        ascii = System.in.read();
        message= message+(char)ascii+"";
       }
   }
   catch(IOException io){
   System.out.println("IOException");
   }
System.out.println("The message is ended");

    String recipient=args[0];         // the data from the command line is entered in appropriate locations
    String machine=args[1];
    sock=new Socket(machine,25);                 // here a Socket is created on machine and SMTP port
    dis = new DataInputStream(sock.getInputStream( ));// a factory method returns the input stream
    isr= new InputStreamReader(dis);                                  // here is an example of layered streams
    bis = new BufferedReader(isr);

    ps=new PrintStream(sock.getOutputStream( ));  // a PrintStream is opened on an OutputStream

   ps.println("mail from: pkomisar@sentex.net");  // The strings being sent are the actually token exchanges
   System.out.println(bis.readLine( ));

   String Addresses=args[0];
   ps.println("rcpt to: " + Addresses);
   System.out.println(bis.readLine());

   ps.println("data");
   System.out.println(bis.readLine());

   ps.println(message +"\n.");       // sending a period on it's own line is part of the protocol. This doesn't
   System.out.println(bis.readLine());   // seem to be satisfied in Dos  but the mail goes through anyway

   ps.flush( );
   sock.close( );
   }
}