/* package group2.shenyang; */
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/*************************************************************************
Name: SMTP2.java

Input: 
4 parameters from a CGI form w/ the following names
email: email address(es)
cc: carbon coby list of email address(es)
subject: hSubject heading for the email
data: Actual email message body

Functionality:
- Parses each email address and cc addresses
- Log into an email server
- send mail to all receiptients
- log out from the email server

Output:
A status web page whether the email was sent success of failure

Error Checks:
- On error, the servlet aborts and dumps error message
**************************************************************************/

 public class SMTP2 extends HttpServlet{

/* The doPost class will handle the request */
    public void doPost(HttpServletRequest req, HttpServletResponse res) 
    throws ServletException, IOException{
        res.setContentType("text/html");
        ServletOutputStream out=res.getOutputStream();
        
        try{
            // ======= Get the parameters from the CGI form =======
            String emaillist=req.getParameter("email");
	    String from=req.getParameter("from");
	    String emaillistorig=emaillist;
            String data=req.getParameter("data");
          String cclist=req.getParameter("cc");
          String ccorig=cclist;
          String subject=req.getParameter("subject");
       
          
          /* we must have at least an email address and data message */
          if (emaillist.equals("")){
              throw new ServletException("Missing Email Address");
          }
          if (data.equals("")){
                throw new ServletException("Missing Data Message");
          }


          String pop_res;
          int ret_code;


          
          // ===== Create socket and log into SMTP =====
          Socket sock=new Socket("iscp.bellcore.com", 25);
          PrintStream in_sock=new PrintStream(sock.getOutputStream());
          DataInputStream out_sock=new DataInputStream(sock.getInputStream());
       
          
          /* make sure we connect fine */
          pop_res=out_sock.readLine();
          ret_code = Integer.parseInt(pop_res.substring(0,3));
          switch (ret_code) {
              case 220:
                  break;
              default: 
                      throw new ServletException("connection returned error: "+pop_res);            
            }   
        
          
          /* send HELO greeting and wait for response */
          in_sock.println("HELO cypress.iscp.bellcore.com");
          pop_res=out_sock.readLine();
          ret_code = Integer.parseInt(pop_res.substring(0,3));
          switch (ret_code) {
              case 250:
                  break;
              default: 
                      throw new ServletException("HELO returned error: "+pop_res);            
            }   

          int counter = 0;


          
          
    
          /* tell smtp who the mail is from */
          in_sock.println("MAIL FROM: "+from);
          pop_res=out_sock.readLine();
          ret_code = Integer.parseInt(pop_res.substring(0,3));
          switch (ret_code) {
              case 250: 
                  break;
              default: 
                  throw new ServletException("MAIL returned error: "+pop_res);            
          }     
      
      
          /* parse the list of email address and make each a receiptient */
          StringTokenizer emailtok=new StringTokenizer(emaillist,",");
          int num;

          for (num = 0; num <= emailtok.countTokens(); num++) {
           
              String email = emailtok.nextToken().trim();
              StringTokenizer tok=new StringTokenizer(email,"@");
              if (tok.countTokens() != 2) {
                  continue;
              }
              String user=tok.nextToken();
              String address=tok.nextToken();

              in_sock.println("RCPT TO: "+user+"@"+address);
              pop_res=out_sock.readLine();
              ret_code = Integer.parseInt(pop_res.substring(0,3));
              switch (ret_code) {
                  case 250: 
                  case 251: out.println("<HTML>Sending mail to "+user+"@"+address+"<BR></HTML>");                           
                      counter+=1;
                      break;
                  case 550: out.println("<HTML>Mailbox unavailable for "+user+"@"+address+"<BR></HTML>");
                      break;
                  case 552: out.println("<HTML>Storage allocation exceeded for "+user+"@"+address+"<BR></HTML>");
                      break;
                  case 553: out.println("<HTML>Mailbox name not allowed for "+user+"@"+address+"<BR></HTML>");
                      break;
                  case 450: out.println("<HTML>Mailbox unavailable for  "+user+"@"+address+"<BR></HTML>");
                      break;
                  case 451: out.println("<HTML>Local error in processing "+user+"@"+address+"<BR></HTML>");
                      break;
                  case 452: out.println("<HTML>insufficient storage "+user+"@"+address+"<BR></HTML>");
                      break;
                  case 551:out.println("<HTML>user not local for "+user+"@"+address+"<BR></HTML>");
                      break;                  
                  default: 
                          throw new ServletException("RCPT returned error: "+pop_res);            
                }
          }


          /* parse the carbon copy list of users and make them receiptments too */
          if (!cclist.equals("")) {
              StringTokenizer cctok=new StringTokenizer(cclist,",");

              for (num = 0; num <= cctok.countTokens(); num++) {
           
                  String cc = cctok.nextToken().trim();
                  StringTokenizer tok=new StringTokenizer(cc,"@");
                  if (tok.countTokens() != 2) {
                      continue;
                  }
                  String user=tok.nextToken();
                  String address=tok.nextToken();

                  in_sock.println("RCPT TO: "+user+"@"+address);
                  pop_res=out_sock.readLine();
                  ret_code = Integer.parseInt(pop_res.substring(0,3));
                  switch (ret_code) {
                      case 250:
                      case 251: out.println("<HTML>Sending mail to "+user+"@"+address+"<BR></HTML>");                           
                          counter+=1;
                          break;
                      case 550: out.println("<HTML>Mailbox unavailable for "+user+"@"+address+"<BR></HTML>");
                          break;
                      case 552: out.println("<HTML>Storage allocation exceeded for "+user+"@"+address+"<BR></HTML>");
                          break;
                      case 553: out.println("<HTML>Mailbox name not allowed for "+user+"@"+address+"<BR></HTML>");
                          break;
                      case 450: out.println("<HTML>Mailbox unavailable for  "+user+"@"+address+"<BR></HTML>");
                          break;
                      case 451: out.println("<HTML>Local error in processing "+user+"@"+address+"<BR></HTML>");
                          break;
                      case 452: out.println("<HTML>insufficient storage "+user+"@"+address+"<BR></HTML>");
                          break;
                      case 551:out.println("<HTML>user not local for "+user+"@"+address+"<BR></HTML>");
                          break;                  
                      default: 
                              throw new ServletException("RCPT returned error: "+pop_res);            
                    }
              }
          }


          /* if no users were successful receiptients */
          if (counter == 0) {
              throw new ServletException("There are no valid users to be mailed");
          }




          /* send the data message, and line beginning with "." will be sent with ".." */
          in_sock.println("DATA");
          pop_res=out_sock.readLine();
          ret_code = Integer.parseInt(pop_res.substring(0,3));
          switch (ret_code) {
              case 354:
                  break;
              default: 
                      throw new ServletException("DATA returned error: "+pop_res);            
            }   

          /* send email to list */
          in_sock.println("To: "+emaillistorig);

          /* send the cc list */ 
          if (!ccorig.equals("")){
                in_sock.println("Cc: "+ccorig);
          }

          /* send subject header */
          if (!subject.equals("")){
                in_sock.println("Subject: "+subject);
          }


          if (!data.equals("")) {
              StringTokenizer datatok=new StringTokenizer(data,"\n");
/*                  out.println("<HTML>"+datatok.countTokens()+"<BR></HTML>");*/
             
              for (num=0; num <= datatok.countTokens();num++)
              {
                  String datastr=datatok.nextToken();
                  if (datastr.startsWith(".")) {
                      in_sock.println("."+datastr);
                  } else {
                      in_sock.println(datastr);
                  }
              }         
          } else {
              in_sock.println("");
          }

          /* end the data with a "\n.\n" */
          in_sock.println(".");
          pop_res=out_sock.readLine();
          ret_code = Integer.parseInt(pop_res.substring(0,3));
          switch (ret_code) {
              case 250:
                  break;
              default: 
                      throw new ServletException("Data message returned error: "+pop_res);            
            }   


          /* end the smtp session */
          in_sock.println("QUIT");
          pop_res=out_sock.readLine();
          ret_code = Integer.parseInt(pop_res.substring(0,3));
          switch (ret_code) {
              case 221:
                  break;
              default: 
                      throw new ServletException("QUIT returned error: "+pop_res);            
            }
          out.println("<HTML>Email Sent</HTML>");
        }
        catch (ServletException e){
            out.println("<HTML><HEAD><TITLE>"+e+"</TITLE></HEAD>");
            out.println("<BODY>"+e+"</BODY></HTML>");
      }
    }
}
         
