/*
 * @(#)MailServlet.java	1.31 97/11/13
 * 
 * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Sun
 * Microsystems, Inc. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sun.
 * 
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
 * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
 * THIS SOFTWARE OR ITS DERIVATIVES.
 * 
 * CopyrightVersion 1.0
 */
import java.io.*;
import java.util.*;
import java.net.InetAddress;

import javax.servlet.*;
import javax.servlet.http.*;

import sun.net.smtp.SmtpClient;

/** Simple mail servlet which processes the form and send an email.  Note: 
 * requires sun.net.smtp.SmtpClient to function.  Also note that it also
 * requires a direct internet connection (no firewalls), or a mailserver
 * running on the webserver's host machine.  To work in other situations,
 * modify the line with "java.sun.com" as the host to include a host within
 * your local network that has the ability to process incoming SMTP mail.
 * Most Unix machines are capable of this.
 * @author  Pavani Diwanji
 * @author  Jim Driscoll
 */
public class MailServlet extends HttpServlet {

/**
 *  Sends email to the user specified by the form's "email" field.
 *  @param res The servlet's response.
 *  @param tab A Dictionary of the fields entered in the form.  
 */
    public void service(HttpServletRequest req, HttpServletResponse res)
	throws IOException
    {
        Enumeration keys;
        String key;
        String value;
	ServletOutputStream out = res.getOutputStream();
        String line = null;
 
        res.setContentType("text/html");

	preamble(out, "Mail Servlet Output");

	out.println("<h1> Form Reply </h1>");
	out.println("<p>");

	String name = req.getParameter("name");
	String email = req.getParameter("e-mail");
	boolean succeed = false;
	PrintStream ps = null;
        SmtpClient sendmail = null;
	if ((name.length() > 0) && (email.length() > 0)) {
	    try {
		    // open smtp connection
		    sendmail = new SmtpClient("java.sun.com");
	            sendmail.from("bogusaddress@pleasefillin");
		    sendmail.to(email);
		    // get printstream
		    ps = sendmail.startMessage();
		    succeed = true;
	    } catch (Exception e) {
		    e.printStackTrace();
		    out.println("Couldn't reach you through javasoft, trying your local"+
		      "machine instead.  You probably are behind a firewall.");
	    }	    
		if (!succeed) {
		    try { //try again, this time, to localhost
		        // open smtp connection
		        sendmail = new SmtpClient(InetAddress.getLocalHost().getHostName());
			sendmail.from(email);
		        sendmail.to(email);
		        // get printstream
		        ps = sendmail.startMessage();
		    } catch (Exception e) {
		        e.printStackTrace();
			out.println("There was an error sending you mail.");
			postamble(out);
			//if we bomb this time, give up
			return;
		    }	    
		}
        
		try {
            // send headers.
		    ps.println("From: "+email);
		    ps.println("To: "+email);
		    ps.println("Subject: Thanks for using JavaWebServer");
		    ps.print("\r\n"); //header area delimiter
    
		    // now send data to it
		    ps.println("Hello " + name + ",");
		    ps.println();
		    ps.println("Thanks for looking at JavaWebServer.");
		    ps.println();
		    ps.println("- JavaWebServer Team.");
		    ps.println("(email was generated by MailServlet).");
	    	
		    ps.flush();
		    ps.close();
		    sendmail.closeServer();
		    out.println("You will get an email thanking you for using the Java Web Server.");
		} catch (Exception e) {
		    e.printStackTrace();
		    out.println("There was an error sending you mail.");
		    postamble(out);
		    return;
		}
	} else 
	    out.println("You need to enter both name and email address");

	postamble(out);
    }

    public String getServletInfo() {
	return "This mail servlet sends email thanking for downloading.";
    }

    private void preamble(ServletOutputStream out, String s)
	throws IOException
    {
        out.println("<HEAD><TITLE> " + s + "</TITLE></HEAD><BODY>");
    }

    private void postamble(ServletOutputStream out)
	throws IOException
    {
        out.println("</BODY>");
	out.flush();
    }
}

