/**
 * Copyright (c) 2003-2004 System Integrator Corporation.
 *                 All Rights Reserved.
 */
package jp.co.sint.mail;

//import java.io.UnsupportedEncodingException; // 7.4.0 ST2060 修正

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMessage;
//import javax.mail.internet.MimeUtility; // 7.4.0 ST2060 修正
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import jp.co.sint.config.SIConfig;
import jp.co.sint.tools.SIFatalException;
import jp.co.sint.tools.SIStringUtil;
import jp.co.sint.tools.SIUtil;

import org.apache.log4j.Category;


/**
 * @version $Id: SIMail.java,v 1.0 2003/10/09 Exp $
 * @author Jinwang Chen
 * <br>Description:javaMailパッケージを通じてメール送信処理を行います。
 * <p>History</p>
 * <p>Author&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Reason</p>
 *  ============&nbsp;&nbsp;&nbsp;==========&nbsp;&nbsp;===========================<br>
 * Jinwang Chen   2003/10/09 11:19:33 Original
 */

public class SIMail {
  //ログ用のインスタンスの生成
  private static Category log=Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);

  //パラメータの定義
  private Message message;

  //ソース名
  private String mailSessionName=SIMailUtil.getSession();

  //ヘッダ名
  private String headerName=SIMailUtil.getHeaderName();

  //返信アドレスリスト
  private Collection replyTo=new ArrayList();

  //宛先リスト
  private Collection to=new ArrayList();

  //CCリスト
  private Collection cc=new ArrayList();

  //BCCリスト
  private Collection bcc=new ArrayList();

  //添付ファイルパート1
  private MimeBodyPart attachmentPart1;

  //添付ファイルパート2
  private MimeBodyPart attachmentPart2;

  //添付ファイルパート3
  private MimeBodyPart attachmentPart3;

  //添付ファイルパート4
  private MimeBodyPart attachmentPart4;

  //添付ファイルパート5
  private MimeBodyPart attachmentPart5;

  /**
   * <b>SIMail</b>
   * コンストラクタ
   * @param なし
   * @return なし
   * @throws なし
   */
  public SIMail() throws SIFatalException{
    try {
      Context initCtx=new InitialContext();
      if(SIConfig.SISERVER_TYPE.equalsIgnoreCase("Tomcat")){//7.1.1 ST0225 追加
        Context envCtx=(Context) initCtx.lookup("java:comp/env");
        Session session = (Session) envCtx.lookup(mailSessionName);
        message=new MimeMessage(session);
      //7.1.1 ST0225 追加 ここから
      }else if(SIConfig.SISERVER_TYPE.equalsIgnoreCase("WebSphere")){
        InitialContext ctx = new InitialContext();
        Session session = (Session) ctx.lookup("java:comp/env/"+mailSessionName);
        message=new MimeMessage(session);
      }
      //7.1.1 ST0225 追加 ここまで
      message.setHeader("X-Mailer",headerName);
      message.setSentDate(new Date());
      message.setFrom(SIMailUtil.getFrom());
      replyTo=SIMailUtil.getReplyTo();
    }catch(NamingException e){
      e.printStackTrace();
      throw new SIFatalException(e);
    }catch(MessagingException e){
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }

  /**
   * <b>setHeaderName</b>
   * ヘッダ名を設定します
   * @param lHeadreName  ヘッダ名
   * @return なし
   * @throws なし
   */
  public void setHeaderName(String lHeadreName)throws SIFatalException{
    this.headerName =SIStringUtil.null2Space(lHeadreName);
    try {
      message.setHeader("X-Mailer", lHeadreName);
    } catch (MessagingException e) {
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }

  /**
   * <b>setFrom</b>
   * 送信者メールを設定する
   * @param from  送信者メールアドレス
   * @return なし
   * @throws AddressException
   * @throws MessagingException
   * @throws UnsupportedEncodingException
   */
  public void setFrom(String from) throws SIFatalException {
    try {
      message.setFrom(new InternetAddress(SIUtil.CP932ToJIS(from)));
    } catch (AddressException e) {
      e.printStackTrace();
      throw new SIFatalException(e);
    } catch (MessagingException e) {
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }

  /**
   * <b>addTo</b>
   * あて先リストを設定する
   * @param lTo  あて先リスト
   * @return なし
   * @throws なし
   */
  public void addTo(String lTo) throws SIFatalException{
    log.info("mailTo="+lTo);
    SIMailUtil.addAddress(to,lTo);
  }

  /**
   * <b>addReplyTo</b>
   * 返信先リストを設定する
   * @param lReplyTo  返信先リスト
   * @return なし
   * @throws なし
   */
  public void addReplyTo(String lReplyTo) throws SIFatalException{
    log.info("replyTo="+lReplyTo);
    SIMailUtil.addAddress(replyTo,lReplyTo);
  }

  /**
   * <b>addCc</b>
   * CC先リストを設定する
   * @param lCc  CC先リスト
   * @return なし
   * @throws なし
   */
  public void addCc(String lCc)throws SIFatalException{
    log.info("cc="+lCc);
    SIMailUtil.addAddress(cc,lCc);
  }
  
  public void addCc(String[] lCc)throws SIFatalException{
    for (int i=0;i<lCc.length;i++) {
      log.info("cc="+lCc[i]);
      SIMailUtil.addAddress(cc,lCc[i]);
    }
  }

  /**
   * <b>addBcc</b>
   * BCC先リストを設定する
   * @param lBcc  BCC先リスト
   * @return なし
   * @throws なし
   */
  public void addBcc(String lBcc)throws SIFatalException{
    log.info("Bcc="+lBcc);
    SIMailUtil.addAddress(bcc,lBcc);
  }

  /**
   * <b>setSubject</b>
   * 件名を設定する
   * @param subject 件名
   * @return なし
   * @throws なし
   */
  public void setSubject(String lSubject)throws SIFatalException{
    if (SIUtil.isNull(lSubject))return;
    try {
    // 7.4.0 ST2060 修正 ここから
      SIEncodeToJis etj = new SIEncodeToJis();
      message.setSubject(etj.encodeHeader(lSubject));
    /*
      message.setSubject(MimeUtility.encodeText(jp.co.sint.tools.SIHTMLUtil.HTMLEncode(lSubject),"ISO-2022-JP","B"));//7.1.1 ST0216 修正
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new SIFatalException(e);
    */
    // 7.4.0 ST2060 修正 ここまで
    } catch (MessagingException e) {
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }

  /**
   * <b>setContent</b>
   * メール内容を設定する
   * @param lContent メール内容
   * @return なし
   * @throws なし
   */
  public void setContent(String lContent)throws SIFatalException{
    if (SIUtil.isNull(lContent)) return;
    try {
    // 7.4.0 ST2060 修正 ここから
      SIEncodeToJis etj = new SIEncodeToJis();
      message.setText(etj.encodeBody(lContent));
      message.setHeader("Content-Type", "text/plain; charset=ISO-2022-JP");
      //message.setContent(SIUtil.CP932ToJIS(lContent),"text/plain; charset=ISO-2022-JP ");
    // 7.4.0 ST2060 修正 ここまで
    } catch (MessagingException e) {
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }

  /**
   * <b>setAttachmentFile</b>
   * 添付ファイル1を設定します。
   * @param lFile 添付ファイル1のFileオブジェクト
   * @param lFileName メールに添付するファイルの名前
   * @throws SIFatalException
   */
  public void setAttachmentFile1(File lFile, String lFileName) throws SIFatalException{
    try{
      attachmentPart1 = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(lFile);
      DataHandler dh = new DataHandler(fds);
      attachmentPart1.setDataHandler(dh);
      attachmentPart1.setFileName(lFileName);
    }catch(MessagingException e){
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }

  /**
   * <b>setAttachmentFile</b>
   * 添付ファイル2を設定します。
   * @param lFile 添付ファイル2のFileオブジェクト
   * @param lFileName メールに添付するファイルの名前
   * @throws SIFatalException
   */
  public void setAttachmentFile2(File lFile, String lFileName) throws SIFatalException{
    try{
      attachmentPart2 = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(lFile);
      DataHandler dh = new DataHandler(fds);
      attachmentPart2.setDataHandler(dh);
      attachmentPart2.setFileName(lFileName);
    }catch(MessagingException e){
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }
  /**
   * <b>setAttachmentFile</b>
   * 添付ファイル3を設定します。
   * @param lFile 添付ファイル3のFileオブジェクト
   * @param lFileName メールに添付するファイルの名前
   * @throws SIFatalException
   */
  public void setAttachmentFile3(File lFile, String lFileName) throws SIFatalException{
    try{
      attachmentPart3 = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(lFile);
      DataHandler dh = new DataHandler(fds);
      attachmentPart3.setDataHandler(dh);
      attachmentPart3.setFileName(lFileName);
    }catch(MessagingException e){
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }
  /**
   * <b>setAttachmentFile</b>
   * 添付ファイル4を設定します。
   * @param lFile 添付ファイル4のFileオブジェクト
   * @param lFileName メールに添付するファイルの名前
   * @throws SIFatalException
   */
  public void setAttachmentFile4(File lFile, String lFileName) throws SIFatalException{
    try{
      attachmentPart4 = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(lFile);
      DataHandler dh = new DataHandler(fds);
      attachmentPart4.setDataHandler(dh);
      attachmentPart4.setFileName(lFileName);
    }catch(MessagingException e){
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }
  /**
   * <b>setAttachmentFile5</b>
   * 添付ファイル5を設定します。
   * @param lFile 添付ファイル5のFileオブジェクト
   * @param lFileName メールに添付するファイルの名前
   * @throws SIFatalException
   */
  public void setAttachmentFile5(File lFile, String lFileName) throws SIFatalException{
    try{
      attachmentPart5 = new MimeBodyPart();
      FileDataSource fds = new FileDataSource(lFile);
      DataHandler dh = new DataHandler(fds);
      attachmentPart5.setDataHandler(dh);
      attachmentPart5.setFileName(lFileName);
    }catch(MessagingException e){
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }

  /**
   * <b>sendMail</b>
   * 送信します.
   * @param true 送信OK false NG
   * @return なし
   */
  public boolean sendMail() throws SIFatalException{
    try {

      //返信先
      if (replyTo!=null){
        message.setReplyTo((InternetAddress[])replyTo.toArray(new InternetAddress[0]));
      }

      //宛先
      if (to!=null){
        message.addRecipients(Message.RecipientType.TO,(InternetAddress[])to.toArray(new InternetAddress[0]));
      }

      //CC先
      if (cc!=null){
        message.addRecipients(Message.RecipientType.CC,(InternetAddress[])cc.toArray(new InternetAddress[0]));
      }

      //BCC先
      if (bcc!=null){
        message.addRecipients(Message.RecipientType.BCC,(InternetAddress[])bcc.toArray(new InternetAddress[0]));
      }

      //本文・添付ファイルの構成
      if(attachmentPart1!=null||attachmentPart2!=null||attachmentPart3!=null||attachmentPart4!=null||attachmentPart5!=null){
        MimeMultipart mmp = new MimeMultipart();
        message.setContent(mmp);
        MimeBodyPart textPart = new MimeBodyPart();
        mmp.addBodyPart(textPart);
        if(attachmentPart1!=null) mmp.addBodyPart(attachmentPart1);
        if(attachmentPart2!=null) mmp.addBodyPart(attachmentPart2);
        if(attachmentPart3!=null) mmp.addBodyPart(attachmentPart3);
        if(attachmentPart4!=null) mmp.addBodyPart(attachmentPart4);
        if(attachmentPart5!=null) mmp.addBodyPart(attachmentPart5);
      }

      // エンコードタイプ明示指定
      message.addHeader("Content-Transfer-Encoding", "7bit");

      //送信
      Transport.send(message);
      log.info("send mail ok!!");
      return true;
    } catch (MessagingException e) {
      e.printStackTrace();
      throw new SIFatalException(e);
    }
  }
}
