/*-------------------------------------------------------------------------*/
/**
 [Project ]: 프레임웍 기반 그룹웨어 시제품 개발
 
 [Date] : 1999. 9. 3
 [Source file]: com/etri/groupware/mail/MailSender.java
 [Vesion] : 1.0
 */
/*--------------------------------------------------------------------------*/




package com.etri.groupware.mail;

import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;

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

import com.etri.groupware.*;


public class MailSender implements MailSenderInterface{
	
	private String protocol = "smtp";
	private String mailHost = null;
	private boolean debugFlag = false;
	
	private Session session;
	
	public MailSender() {
		System.out.println("Connect to localhost...");
		 initialize();
	}
	
	public MailSender(String protocol, String mailHost) {
		this.protocol = protocol;
		this.mailHost = mailHost;
		initialize();
		
		System.out.println("Connected to " + mailHost + " Server with " + protocol + " protocol");
		
	}
	
	public void initialize() {
			Properties props = new Properties();
			props.put("mail.smtp.host", mailHost);

			session = Session.getDefaultInstance(props, null);
		    
			if (debugFlag){
		    	session.setDebug(true);
		    }

	}


     public ResultStatus sendMail(MailInfo mi) throws Exception {
     	ResultStatus rs;
     	
        if( mi.getAttachedFiles() == null) { 	
        	rs = sendTextMail(mi);      	
        }
     	else {
     		rs = sendMultiPartMail(mi);
     	}
     	
     	return rs;
     }
     
     public ResultStatus sendMail(MailInfo mi, String id, String password) throws Exception {
     	ResultStatus rs;
     	
        if( mi.getAttachedFiles() == null) { 	
        	rs = sendTextMail(mi, id, password);      	
        }
     	else {
     		rs = sendMultiPartMail(mi, id, password);
     	}
     	
     	return rs;
     }
     
     protected ResultStatus sendMultiPartMail(MailInfo mi) throws Exception {
     	
     	return sendMultiPartMail(mi, null, null );
     }


	
	protected ResultStatus sendMultiPartMail(MailInfo mi, String id, String password) throws Exception {
		
		String from = mi.getFrom();
   		InternetAddress[] toary = convertStringToAddress(mi.getToArray());
   		
		InternetAddress[] ccary  = null;
   		if (mi.getCcArray() != null ) {
   			ccary = convertStringToAddress(mi.getCcArray());
   		}
   		
   		InternetAddress[] bccary = null ; 
   		if (mi.getBccArray() != null) {
   			bccary = convertStringToAddress(mi.getBccArray());
   			
   		}
		
		String subject = mi.getSubject();
   		String textContent = mi.getTextContent();
		
		 MimeMessage msg = new MimeMessage(session);
		   	
         if (from != null){
		 		msg.setFrom(new InternetAddress(from));
		 }
		else{
				msg.setFrom();
		}

		// Primary 받는 사람           	
		msg.setRecipients(javax.mail.Message.RecipientType.TO, toary);

		// Carbon Copy 받을 사람
		if (ccary != null){
			msg.setRecipients(javax.mail.Message.RecipientType.CC, ccary);
		}
      	
		// Blind Carbon Copy 받을 사람
	    if (bccary != null){
	    	msg.setRecipients(javax.mail.Message.RecipientType.BCC,	bccary);
	    }

	    msg.setSubject(subject);

	    msg.setHeader("X-Mailer", "msgsend");
		Date sendDate  = new Date(System.currentTimeMillis());
	    msg.setSentDate(sendDate);
			
		MimeBodyPart[] mbp =  makeMimeBodyParts(mi);					
				

		Multipart mp = new MimeMultipart();
				
				
		for ( int i=0;  i< mbp.length; i++){
	
			mp.addBodyPart(mbp[i]);
	
		}					
				
		msg.setContent(mp);	

		Transport.send(msg);
		
		if ( id != null ) {
		
			storeToSentBox(msg, id, password);
		}
		
		return new ResultStatus(ResultStatus.SUCCESS);
      	
	}
	
	protected MimeBodyPart[] makeMimeBodyParts(MailInfo mi)  throws Exception {
		
		int totalBodyNum = 1;
		
		File[] attachedFiles = mi.getAttachedFiles();
		String textContent = mi.getTextContent();
		
		if (attachedFiles !=null ) {
			totalBodyNum += attachedFiles.length ;
		}
		
		MimeBodyPart[] mbp = new MimeBodyPart[totalBodyNum];
		
		mbp[0] = new MimeBodyPart();
		try {
				mbp[0].setText(textContent, javax.mail.internet.MimeUtility.mimeCharset("EUC-KR")  );	
	
				if (attachedFiles != null ) {
					
					String attachedFileName = null;
					
					for ( int i = 1 ; i< totalBodyNum; i++) {
						mbp[i] = new MimeBodyPart();
			
						FileDataSource fds = new FileDataSource(attachedFiles[i-1]);
     		  			mbp[i].setDataHandler(new DataHandler(fds));
     		  			
     		  			String tempName = attachedFiles[i-1].getName();
     		  			attachedFileName = MimeUtility.encodeText(tempName, "EUC-KR", "Q");
     		  			     		  				     		  			
						mbp[i].setFileName(attachedFileName);
						
					}
				}	
		}catch ( javax.mail.MessagingException e){
			System.out.println( e);	
		}
		
		return mbp;
		
	}
	
	protected ResultStatus sendHTMLMail(MailInfo mi) {
		return null;
		
	}
   	   	
   	protected ResultStatus sendTextMail(MailInfo mi) throws Exception {
   		
   		return sendTextMail(mi, null, null);
   	}
   	
   	   	
   	protected ResultStatus sendTextMail(MailInfo mi, String id, String password) throws Exception {
   		
   		String from = mi.getFrom();
   		
   		InternetAddress[] toary = convertStringToAddress(mi.getToArray());
   		
   		InternetAddress[] ccary  = null;
   		if (mi.getCcArray() != null ) {
   			ccary = convertStringToAddress(mi.getCcArray());
   		}
   		
   		InternetAddress[] bccary = null ; 
   		if (mi.getBccArray() != null) {
   			bccary = convertStringToAddress(mi.getBccArray());
   			
   		}
   		
   		String subject = mi.getSubject();
   		String textContent = mi.getTextContent();
   		

   		
		MimeMessage msg2 = new MimeMessage(session);

		if (from != null){
	  		msg2.setFrom(new InternetAddress(from));
		}
		else{
			msg2.setFrom();
		}

			//	 다중 메시지 전송 Test

		msg2.setRecipients(javax.mail.Message.RecipientType.TO, toary);
	
    	if(ccary != null) {
				msg2.setRecipients(javax.mail.Message.RecipientType.CC,ccary);
   		}
			
	    if (bccary != null){
	    	msg2.setRecipients(javax.mail.Message.RecipientType.BCC,bccary);
	    }

		msg2.setSubject(subject);

		msg2.setText(textContent, javax.mail.internet.MimeUtility.mimeCharset("EUC-KR") );

		msg2.setHeader("X-Mailer", "msgsend");
			
		Date sendDate  = new Date(System.currentTimeMillis());
	    msg2.setSentDate(sendDate);

		Transport.send(msg2);
		
		if ( id !=null) {
			storeToSentBox(msg2, id, password);
		}
   		
   		return new ResultStatus(ResultStatus.SUCCESS);

	    
   	}
   	
   	void storeToSentBox(Message m, String id, String password ) throws Exception {
   		
   		ReceiveMailServerManager mailServer = new ReceiveMailServerManager( MailController.receiveMailServerIP,  id, password);
   		
   		mailServer.connect();
   		
   		mailServer.addMail("보낸 편지함", m);
   		mailServer.disconnect();
   		
   	}
	
	protected InternetAddress[] convertStringToAddress(String[] stringAddresses ){
		
		InternetAddress[] addresses = null ;
		try {
	        addresses = new InternetAddress[stringAddresses.length];
		
    	    for(int i = 0; i < stringAddresses.length ; i++)	{ 
    	    	addresses[i] = new InternetAddress(stringAddresses[i]); 
    	    }
			
		}
		catch( javax.mail.internet.AddressException e) {
			System.out.println(e);
		}
		return addresses;

	}
	
	public void setDebug(boolean debugFlag) {
		this.debugFlag = debugFlag;
	}
	
	
	
}