package kr.co.kihyun.mail;

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

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 javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
@WebServlet("/servlet/kr.co.kihyun.mail.SendMail")
public class SendMail extends HttpServlet implements Runnable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String host = "127.0.0.1";
	String sender = "";// 보내는 사람 주소
	String receiver = "";// 받는 사람 주소
	String topic = "";// 제목
	String content = "";// 내용
	String mime = "";// 문서 타입

	public SendMail() {
	}

	public SendMail(String sender2, String receiver2, String topic2, String content2, String mime2) {
		sender = sender2;
		receiver = receiver2;
		topic = topic2;
		// content= toKR(content2); //한글이 안됨.
		content = content2;
		mime = mime2;
	}

	public void run() {
		send();
	}

	public boolean send() {
		Properties props = new Properties();
		props.put("mail.smtp.host", host);

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

		try {
			Message msg = new MimeMessage(session);
			String receiver_tmp = "";
			StringTokenizer stk = new StringTokenizer(receiver, "/");
			int stkCnt = stk.countTokens();
			InternetAddress[] address = new InternetAddress[stkCnt];
			int i4 = 0;
			while (stk.hasMoreTokens()) {
				receiver_tmp = stk.nextToken();
				address[i4] = new InternetAddress(receiver_tmp);
				i4++;
			}

			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setFrom(new InternetAddress(sender));
			msg.setSubject(topic);
			msg.setSentDate(new Date());

			if (mime.equals("text")) {
				msg.setText(content); // TEXT형식
			} else {
				msg.setContent(content, "text/html; charset=UTF-8"); // HTML형식
			}

			Transport.send(msg);

			return true;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static String toKR(String str1) throws UnsupportedEncodingException {

		if (str1 == null) {
			return ("");
		}

		return (new String(str1.getBytes("latin1"), "KSC5601"));
	}
}
