package utils.common.mail;
/*
	*	Name   	: sendAttachMail.java
	*	Author 	: K.S.Shan.
	*	Date	: 3/3/2004
	*	mail	: ksshan@gmail.com
**/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.common.trace.Debug;

//====================

public class sendAttachMail	extends HttpServlet {

	private	static	final	String		SMTP_HOST_NAME		= "mail.shan.com";			// give ur SMTP server name
	private	static	final	String		SMTP_AUTH_USER		= "admin@changepond.com";	// give ur SMTP server user name
	private	static	final	String		SMTP_AUTH_PWD		= "n1mdacc"; 				// give ur SMTP pasword
	private	static	final	int			NO_OF_ATTACHEMENTS	= 3;						// give total attachment size
	private	static	final	String		UPLOADED_FOLDER		= "D:/uploads/";			// give attachment folder location
	private	static			String		MESSAGES_START		= "txtFileName";
	private					BodyPart	messageBodyPart;
	private					Vector 		attachFilesVector;
	private					Debug		log					=	null;
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
    log =	 Debug.getInstance();
    log.debug("Inside doGet Method of the Servlet...");
    doPost(request,response);
}

public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
			log =	 Debug.getInstance();
    		log.debug("Inside the doGet method of the Servlet-- Started Processing Mail !");
			PrintWriter out					=	response.getWriter();
			try{
				String	to					=	request.getParameter("txtTo");
				String	to_cc				=	request.getParameter("txtCC");
				String	to_bcc				=	request.getParameter("txtBCC");
				String	from				=	request.getParameter("txtFrom");
				String	subj				=	request.getParameter("txtSub");
				String	mesg				=	request.getParameter("yourFieldNameHere");

				Vector	emailList_To		=	new Vector();
				Vector	emailList_CC		=	new Vector();
				Vector	emailList_BCC		=	new Vector();

					 	emailList_To		=	getToUsers(to);
					 	emailList_CC		=	getToUsers(to_cc);
					 	emailList_BCC		=	getToUsers(to_bcc);

					attachFilesVector		= 	new Vector();
					attachFilesVector		=	getFileNames(request);

				log.debug("EMAIL TO  LIST  : "+emailList_To);
				log.debug("EMAIL CC  LIST  : "+emailList_CC);
				log.debug("EMAIL BCC LIST  : "+emailList_BCC);
				log.debug("MAIL GETTTING POSTED ");

				postMail( emailList_To,emailList_CC ,emailList_BCC,subj, mesg, from,attachFilesVector);
				out.println("<html><body><b><font color=darkblue face=verdana size=2px>Send... <font></b>");
				out.println("<hr size=5 width=50% align=left color=blue color=blue></body></html>");

				log.debug("MAIL POSTED SUCCESSFULLY ");

				}catch(Exception exe)
				{
					log.debug("EXCEPTION IN SENDING MAIL .. "+exe.getCause().toString());
					out.println("Exception.... Could not Send Mail ..");
					out.println("<hr size=5 width=50% align=left color=red>");
					exe.printStackTrace();
				}
}
/*
		Function which forms the mail body and sends the message.
		@author : k.s.shan
*/
public void postMail( Vector recipients,Vector recipientsCC,Vector recipientsBCC, String subject, String message , String from, Vector AttachmentVector)
	{
	try{
			Properties prop		=	System.getProperties();
			InternetAddress[] addressTo;
			InternetAddress[] addressCC;
			InternetAddress[] addressBCC;

			prop.put("mail.smtp.host",SMTP_HOST_NAME);
			prop.put("mail.smtp.auth","true");

			Authenticator auth  = new MailAuthenticator();

			Session ses1		= Session.getDefaultInstance(prop,auth);
			MimeMessage msg		= new MimeMessage(ses1);

			msg.setFrom(new InternetAddress(from));

			addressTo			= new InternetAddress[recipients.size()];
			addressCC 			= new InternetAddress[recipientsCC.size()];
			addressBCC			= new InternetAddress[recipientsBCC.size()];

			for (int i = 0; i < recipients.size(); i++){
				addressTo[i] 	= new InternetAddress((String)recipients.elementAt(i));
			}
			for (int i = 0; i < recipientsCC.size(); i++){
				addressCC[i] 	= new InternetAddress((String)recipientsCC.elementAt(i));
			}
			for (int i = 0; i < recipientsBCC.size(); i++){
				addressBCC[i]	 = new InternetAddress((String)recipientsBCC.elementAt(i));
			}

			msg.setRecipients(Message.RecipientType.TO, addressTo);
			msg.setRecipients(Message.RecipientType.CC, addressCC);
			msg.setRecipients(Message.RecipientType.BCC,addressBCC);
			msg.setSubject(subject);
			msg.addHeader("X-Priority", "1");

			// Create the message part
			messageBodyPart = new MimeBodyPart();

			// Fill the message
			messageBodyPart.setText(message);
			messageBodyPart.setContent(message,"text/html");

			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(messageBodyPart);

			// Part two is attachment
			if((AttachmentVector != null) &&(AttachmentVector.size() >0)){
				messageBodyPart = doAttachement(AttachmentVector,messageBodyPart);
				log.debug("Going to Add Attachment . ");
				multipart.addBodyPart(messageBodyPart);
			}
			msg.setContent(multipart);
			Transport.send(msg);
			log.debug("MAIL IS SEND SUCCESSFULLY ");
		}
		catch(MessagingException me){
		    log.debug("MESSAGING EXCEPTION "+ me);
			System.out.println("Unable to Send Mail .. "+me);
			me.printStackTrace();
		}
		catch(Exception e){
		    log.debug(" EXCEPTION OCCURED "+ e.getCause().toString());
			//e.printStackTrace();
		}
 }
/***
 	* 	Helper functions which gets the list the users frm the Required String
	*	@author : shan.
	*	input paramater
	*	@string toNames
*/
 private Vector getToUsers(String txtTo)
{
	StringTokenizer st = new StringTokenizer(txtTo,",");
	Vector toUsers	= new Vector();
	Vector users  	= new Vector();
	String temp="";
		while (st.hasMoreTokens()){
			toUsers.add(st.nextToken());
		}
		for(int i=0;i<toUsers.size();i++){
			temp = (String)toUsers.elementAt(i);
			if(temp.indexOf("<")==1){
				temp = temp.substring(temp.indexOf("<")+1,temp.indexOf(">"));
				users.add(temp);
			}else{
				users.add(temp);
			}
		}
	return toUsers;
}
/*		USAGE 			:	Gets the file names from the Mail Page
 *		@author			:	Shan.K.S.
 *		@input paramter :	HttpServletRequest
 */
private Vector getFileNames(HttpServletRequest request)
{
	Vector	fileName	=	new Vector();
	char 	fileEndName	=	'A';
	String  attachFile	=	"";
	for(int counter=1;counter<=NO_OF_ATTACHEMENTS;counter++)
	{
		attachFile 	=	request.getParameter(MESSAGES_START+fileEndName);
		attachFile	= 	attachFile.replaceAll(" ","");
		if(!attachFile.equals("***") || (!attachFile.equals("")) || attachFile != null){
			fileName.add(attachFile);
		}
		fileEndName++;
	}
	log.debug("Return File Name : "+fileName);
	return fileName;
}
private BodyPart doAttachement(Vector fileVector,BodyPart messageBodyPart) throws MessagingException
{
		messageBodyPart 	= new MimeBodyPart();
		String 	name		= "";

		for(int i = 0;i<fileVector.size();i++){
			name =	(String)fileVector.elementAt(i);
			name =	 name.replaceAll(" ","");
			if(!name.equals("***")){
			DataSource source 	= new FileDataSource(UPLOADED_FOLDER+(String)fileVector.elementAt(i));
			messageBodyPart.setDataHandler(new DataHandler(source));
			messageBodyPart.setFileName((String)fileVector.elementAt(i));
			}
		}
		log.debug("Attachment Added Successfully ");
		return messageBodyPart;
}
public static void main(String args[])
{
	// Dummy implementation of main method.
}

}