/*
 * @(#)sendfile.java	1.8 00/05/24
 *
 * Copyright 1996-2000 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */

import java.util.*;
import java.io.*;
import java.io.PrintStream;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

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


/**
 * sendfile will create a multipart message with the second
 * block of the message being the given file.<p>
 *
 * This demonstrates how to use the FileDataSource to send
 * a file via mail.<p>
 *
 * usage: <code>java sendfile <i>to from smtp file true|false</i></code>
 * where <i>to</i> and <i>from</i> are the destination and
 * origin email addresses, respectively, and <i>smtp</i>
 * is the hostname of the machine that has smtp server
 * running.  <i>file</i> is the file to send. The next parameter
 * either turns on or turns off debugging during sending.
 *
 * @author	Christopher Cotton
 */

public class sendfile extends HttpServlet {

	public void doPost(HttpServletRequest req,
                           HttpServletResponse resp)

		throws ServletException, java.io.IOException
		{

                    boolean b_sucesso = true;

                    // declara o dispositivo de saída.
                    PrintWriter output;

                    // define o tipo de saída.
		    resp.setContentType( "text/html" );

                    // define no dispositivo de saída, o tipo de saída.
		    output = resp.getWriter();

                    // enumera os parâmetros.
		    //Enumeration s_Parametros = req.getParameterNames();



			// Get Parameter


                      String to = req.getParameter("fld_to");
                      String from = req.getParameter("fld_from");
                      String host = req.getParameter("fld_smtphost");
                      String filename = req.getParameter("fld_filename");
                      //boolean debug = Boolean.valueOf(req.getParameter("fld_filename_yn")).booleanValue();
                      boolean debug = true;
                      String msgText1 = "Sending a file.\n";
                      String subject = "Sending a file";

                      // create some properties and get the default Session
                      Properties props = System.getProperties();
                      props.put("mail.smtp.host", host);

                      Session session = Session.getDefaultInstance(props, null);
                      session.setDebug(debug);

			try {

                            // criando arquivo de log
                            PrintStream saidaPadraoEErro = new PrintStream( new FileOutputStream("usr/local/web/vesper/servlet/sendfile.log", true), true );
                            System.setErr(saidaPadraoEErro);
                            System.setOut(saidaPadraoEErro);




			    // create a message
			    MimeMessage msg = new MimeMessage(session);
			    msg.setFrom(new InternetAddress(from));
			    InternetAddress[] address = {new InternetAddress(to)};
			    msg.setRecipients(Message.RecipientType.TO, address);
			    msg.setSubject(subject);

			    // create and fill the first message part
			    MimeBodyPart mbp1 = new MimeBodyPart();
			    mbp1.setText(msgText1);

			    // create the second message part
			    MimeBodyPart mbp2 = new MimeBodyPart();

		            // attach the file to the message
		   	    FileDataSource fds = new FileDataSource(filename);
			    mbp2.setDataHandler(new DataHandler(fds));
			    mbp2.setFileName(fds.getName());

			    // create the Multipart and its parts to it
			    Multipart mp = new MimeMultipart();
			    mp.addBodyPart(mbp1);
			    mp.addBodyPart(mbp2);

			    // add the Multipart to the message
			    msg.setContent(mp);

			    // set the Date: header
			    msg.setSentDate(new Date());

			    // send the message
			    Transport.send(msg);

                          }

                            /*
                            catch (FileNotFoundException fnfExc) {
                            System.out.println("InscricaoSaServlet01 -Não conseguiu criar arquivo de log");
                            System.exit(0);
                            } // catch
                            */

					catch (MessagingException mex) {
                                            b_sucesso = false;

					    //mex.printStackTrace();
                                            System.out.println(mex);

					    Exception ex = null;
					    if ((ex = mex.getNextException()) != null) {
						//ex.printStackTrace();
                                                System.out.println(ex);
					    } // fecha catch (MessagingException mex)

				} //fecha Try
                                sendResponse( b_sucesso, output );
		    } // public void doPost


                    public void sendResponse( boolean p_b_sucesso, PrintWriter p_output )
                    {
                        p_output.println( "<html>\n" );
                        p_output.println( "<head><title>Vesper</title></head>\n" );
                        if (p_b_sucesso == true)
                          p_output.println( "Formulario enviado com sucesso !!!\n" );
                          else
                            p_output.println( "Formulario com ERRO !!!\n" );


                        p_output.println( "</body>\n" );
                        p_output.println( "</html>" );



                    } // sendResponse

} // public class sendfile extends HttpServlet

