package jp.agentec.sinaburocast.common.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.seasar.framework.util.StringUtil;

/**
 * メール送信ユーティリティクラス
 *
 * @author tsukada
 *
 */
public class MailUtil {
	private static final Logger LOGGER = Logger.getLogger(MailUtil.class);

	/**
	 * メールを送信する。
	 * 引数以外はプロパティファイルから値を取得。
	 *
	 * @param to
	 * @param body
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public static String send(String to, String body) throws MessagingException,UnsupportedEncodingException {
		String smtphost = PropertyUtil.getProperty("SMTP_HOST");
		String from = PropertyUtil.getProperty("DEFAULT_MAIL_FROM_ADDRESS");
		String fromName = PropertyUtil.getProperty("DEFAULT_MAIL_FROM_NAME");
		String subject = PropertyUtil.getProperty("DEFAULT_MAIL_SUBJECT");

		return send(smtphost, from, fromName, to, subject, body);
	}

	/**
	 * メールを送信する。
	 * 引数以外はプロパティファイルから値を取得。
	 *
	 * @param to
	 * @param body
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public static String send(String to, String subject, String body) throws MessagingException,UnsupportedEncodingException {
		String smtphost = PropertyUtil.getProperty("SMTP_HOST");
		String from = PropertyUtil.getProperty("DEFAULT_MAIL_FROM_ADDRESS");
		String fromName = PropertyUtil.getProperty("DEFAULT_MAIL_FROM_NAME");

		return send(smtphost, from, fromName, to, subject, body);
	}
	public static String  send(String smtphost, String from, String fromName, String to, String subject, String body) throws MessagingException, UnsupportedEncodingException {
		String smtpAuthId = PropertyUtil.getProperty("DEFAULT_SMTP_AUTH_ID");
		String smtpAuthPass = PropertyUtil.getProperty("DEFAULT_SMTP_AUTH_PASS");

		if (StringUtils.isNotEmpty(smtpAuthId)) { // smtp authで送信
	 		return send(smtphost, from, fromName, to, subject, body, smtpAuthId, smtpAuthPass);
		}
		else {
	 		return send(smtphost, from, fromName, to, subject, body, null, null);
		}
	}

	/**
	 * メールを送信する。
	 *
	 * @param smtphost
	 * @param from
	 * @param fromName
	 * @param to
	 * @param subject
	 * @param body
	 * @param smtpAuthId smtpauthで送信しない場合はnull
	 * @param smtpAuthPass
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public static String  send(String smtphost, String from, String fromName, String to, String subject, String body, String smtpAuthId, String smtpAuthPass) throws MessagingException, UnsupportedEncodingException {

		String messageId = null;

		Properties props = System.getProperties();
		props.put("mail.smtp.host", smtphost);
		//choi-c
		if(!StringUtil.isEmpty(PropertyUtil.getProperty("SMTP_PORT"))){
			props.put("mail.smtp.port", PropertyUtil.getProperty("SMTP_PORT"));//587
		}
		//choi-c END
		if (smtpAuthId != null && SinaburoUtil.isNotBlankOrSpace(smtpAuthId)) {
			props.put("mail.smtp.auth","true");
		}

		Session session = Session.getDefaultInstance(props, null);
		MimeMessage mimeMessage = new MimeMessage(session);
		mimeMessage.setFrom(new InternetAddress(from, fromName, "UTF-8"));
		mimeMessage.setRecipients(Message.RecipientType.TO, to);
		mimeMessage.setSubject(subject, "UTF-8");
		mimeMessage.setText(body, "UTF-8");
		mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");
		mimeMessage.setSentDate(new Date());
		mimeMessage.getMessageID();

		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("from: " + from);
			LOGGER.debug("fromName: " + fromName);
			LOGGER.debug("to: " + to);
			LOGGER.debug("subject: " + subject);
			LOGGER.debug("body:\n" + body);
		}

		// 送信する
		if (smtpAuthId == null || SinaburoUtil.isBlankOrSpace(smtpAuthId)) {
			Transport.send(mimeMessage);
			messageId = mimeMessage.getMessageID();
		}
		else { // smtpauthで送信
			Transport transport = session.getTransport("smtp");
			transport.connect(null, smtpAuthId, smtpAuthPass);
			transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
			messageId = mimeMessage.getMessageID();
			transport.close();
		}
		return messageId;
	}

	/**
	 * メールを送信する。
	 */
	public static String send(String smtphost, String from, String fromName, Address[] to, Address[] bcc, String cc, String subject, String body, String smtpAuthId, String smtpAuthPass) throws MessagingException, UnsupportedEncodingException {

		String messageId = null;

		Properties props = System.getProperties();
		props.put("mail.smtp.host", smtphost);
		//choi-c
		if(!StringUtil.isEmpty(PropertyUtil.getProperty("SMTP_PORT"))){
			props.put("mail.smtp.port", PropertyUtil.getProperty("SMTP_PORT"));//587
		}
		//choi-c END
		if (smtpAuthId != null && SinaburoUtil.isNotBlankOrSpace(smtpAuthId)) {
			props.put("mail.smtp.auth","true");
		}

		Session session = Session.getDefaultInstance(props, null);
		MimeMessage mimeMessage = new MimeMessage(session);
		mimeMessage.setFrom(new InternetAddress(from, fromName, "UTF-8"));

		if (to != null && to.length > 0) {
			mimeMessage.setRecipients(Message.RecipientType.TO, to);
		} else {
			LOGGER.error("alertMail [to] is null or size 0 .......................................!!");
		}

		if (!SinaburoUtil.isBlankOrSpace(cc)) {
			mimeMessage.setRecipients(Message.RecipientType.CC, cc);
		}
		if (bcc != null && bcc.length > 0) {
			mimeMessage.setRecipients(Message.RecipientType.BCC, bcc);
		}
		mimeMessage.setSubject(subject, "UTF-8");
		mimeMessage.setText(body, "UTF-8");
		mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");
		mimeMessage.setSentDate(new Date());

		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("from: " + from);
			LOGGER.debug("fromName: " + fromName);
			if (to != null) {
				String addresses = "";
				for (Address address : to) {
					addresses = addresses + address.toString() + ";";
				}
				LOGGER.debug("to: " + addresses);
			}
			LOGGER.debug("cc: " + cc);
			LOGGER.debug("bcc: " + bcc);
			LOGGER.debug("subject: " + subject);
			LOGGER.debug("body:\n" + body);
		}
		// 送信する
		if (smtpAuthId == null || SinaburoUtil.isBlankOrSpace(smtpAuthId)) {
			Transport.send(mimeMessage);
			messageId = mimeMessage.getMessageID();
		}
		else {
			// smtpauthで送信
			Transport transport = session.getTransport("smtp");
			transport.connect(null, smtpAuthId, smtpAuthPass);
			transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
			messageId = mimeMessage.getMessageID();
			transport.close();
		}

		return messageId;
	}

	public static void main(String[] args) {
		try {
			if (args.length != 6 && args.length != 8) {
				System.out.println("usage: java -cp .;mail.jar MailUtil <smtphost> <to> <from> <fromName> <subject> <body>");
				System.out.println("usage: java -cp .;mail.jar MailUtil <smtphost> <to> <from> <fromName> <subject> <body> <smtpAuthId> <smtpAuthPass>");
				return;
			}
			String smtphost = args[0];
			String to = args[1];
			String from = args[2];
			String fromName = args[3];
			String subject = args[4];
			String body = args[5];
			String smtpAuthId = (args.length == 8)? args[6]: "";
			String smtpAuthPass = (args.length == 8)? args[7]: "";

			if (args.length == 6) {
				send(smtphost, from, fromName, to, subject, body);
			}
			else {
				send(smtphost, from, fromName, to, subject, body, smtpAuthId, smtpAuthPass);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}