package mobvista.dmp.util;

import org.apache.log4j.Logger;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.Date;
import java.util.Properties;

/**
 * 发送邮件
 * @author fengliang
 */
public class MailUtil {
	private static final String HOST = "smtp.exmail.qq.com";
	private static final String FROM = "monitor.dataPlatform@mobvista.com";
	private static final String USERNAME = "monitor.dataPlatform@mobvista.com";
	private static final String PASSWORD = "dataPlatform1";
	private static final Logger log = Logger.getLogger(MailUtil.class);
	
	public static void sendEmail(String to, String subject, String body)
			throws MessagingException, java.io.UnsupportedEncodingException {
		Transport transport = null;
		try {
			Properties props = new Properties();
			props.setProperty("mail.smtp.auth", "true");// 指定是否需要SMTP验证
			props.setProperty("mail.smtp.host", HOST);// 指定SMTP服务器
			props.put("mail.transport.protocol", "smtp");
			Session mailSession = Session.getDefaultInstance(props);
			mailSession.setDebug(false);// 是否在控制台显示debug信息

			log.info("Will send mail to " + to);
			InternetAddress fromAddress = new InternetAddress(FROM);
			InternetAddress toAddress = new InternetAddress(to);

			MimeMessage testMessage = new MimeMessage(mailSession);
			testMessage.setFrom(fromAddress);
			testMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
			testMessage.setSentDate(new Date());
			testMessage.setSubject(MimeUtility.encodeText(subject, "utf-8", "B"));

			testMessage.setContent(body, "text/html;charset=utf-8");

			transport = mailSession.getTransport("smtp");
			transport.connect(HOST, USERNAME, PASSWORD);
			transport.sendMessage(testMessage, testMessage.getAllRecipients());
		} finally {
			if (transport != null) {
				transport.close();
			}
		}
	}
}
