package com.ekexiu.portal.mail;

import java.util.Map;
import java.util.Properties;

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.MimeMessage;

import org.jfw.apt.annotation.Bean;

@Bean
public class MailService {
	private Properties sessionProperties = new Properties();;
	private String mailHost;
	private int port;
	private String username;
	private String password;
	private Session session;
	private String from;

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	private Session getSession() {
		if (null == this.session) {
			this.session = Session.getInstance(this.sessionProperties);
		}
		return this.session;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public Properties getSessionProperties() {
		return sessionProperties;
	}

	public void setSessionProperties(Map<String, String> map) {
		this.sessionProperties.clear();
		this.sessionProperties.putAll(map);
	}

	public String getMailHost() {
		return mailHost;
	}

	public void setMailHost(String mailHost) {
		this.mailHost = mailHost;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void sendSimpleMail(String to, String template, Map<String, String> values, String subject) throws MessagingException {
		Transport ts = this.getSession().getTransport();
		ts.connect(this.mailHost, port, username, password);
		try {
			Message message = this.createSimpleMail(to, subject, template, values);
			ts.sendMessage(message, message.getAllRecipients());
		} finally {
			try {
				ts.close();
			} catch (Exception e) {
			}
		}
	}

	private MimeMessage createSimpleMail(String to, String subject, String template, Map<String, String> values) throws AddressException, MessagingException {
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(this.from));
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
		message.setSubject(subject);

		String content = template;
		if (null != values && values.size() > 0) {
			for (Map.Entry<String, String> entry : values.entrySet()) {
				content = content.replaceAll(entry.getKey(), entry.getValue());
			}
		}
		message.setContent(content, "text/html;charset=UTF-8");
		return message;
	}
}
