/**
 * 
 */
package jp.ac.naka.ec.plugin.mail;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;

/**
 * XMLでメッセージをラップして送信
 * 
 * @author Takashi Kasuya
 * 
 */
public class MailBodyParserImpl implements MailBodyParser {

	SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");

	/*
	 * (non-Javadoc)
	 * 
	 * @see jp.ac.naka.ec.plugin.mail.MailBodyParser#parseMessageBody()
	 */
	public String parseMailBody(Message message) {
		StringBuilder sb = new StringBuilder();
		Address[] addr = null;

		try {
			if ((addr = message.getFrom()) != null) {
				for (int j = 0; j < addr.length; j++) {
					sb.append("<from><![CDATA[");
					sb.append(addr[j]);
					sb.append("]]></from>");
				}
			}
		} catch (MessagingException e) {

		}

		// TO
		try {
			if ((addr = message.getRecipients(Message.RecipientType.TO)) != null) {
				for (int j = 0; j < addr.length; j++) {
					sb.append("<to>");
					sb.append(addr[j].toString());
					sb.append("</to>");
				}
			}
		} catch (MessagingException e) {
		}

		// SUBJECT

		try {
			sb.append("<subject>");
			sb.append(message.getSubject());
			sb.append("</subject>");
		} catch (MessagingException e) {
			e.printStackTrace();
		}

		// DATE
		Date d;
		try {
			d = message.getSentDate();
			if (d != null) {
				sb.append("<date>");
				sb.append(formatter.format(d));
				sb.append("</date>");
			}
		} catch (MessagingException e) {
		}

		return sb.toString();
	}

}
