package com.yeejoin.amos.supervision.business.util;

import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.Date;
import java.util.Properties;

public class MailUtil {
	/**
	 * 发送邮件
	 * @param context 内容
	 * @param title 标题
	 * @param host smtphost
	 * @param sendder 发送者
	 * @param to 发送给谁
	 * @param pass
	 */
	public static void sendMail(String context, String title, String host, String sendder,String pass,
			Address[] to) {
		try {
			Properties prop = new Properties();
			prop.setProperty("mail.transport.protocol", "smtp"); // 协议
			prop.setProperty("mail.smtp.host", host); // 主机名
			prop.setProperty("mail.smtp.auth", "true"); // 是否开启权限控制
			prop.setProperty("mail.debug", "true"); // 返回发送的cmd源码
			prop.setProperty("mail.smtp.port", "443");
			Session session = Session.getInstance(prop);
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(sendder)); // 自己的email
			msg.setRecipients(RecipientType.TO, to);
			msg.setSubject(title);// 邮件标题
			msg.setText(context);// 邮件正文
			// 不被当作垃圾邮件的关键代码--Begin ，如果不加这些代码，发送的邮件会自动进入对方的垃圾邮件列表
			msg.addHeader("X-Priority", "3");
			msg.addHeader("X-MSMail-Priority", "Normal");
			msg.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
			msg.addHeader("X-MimeOLE", "Produced By Microsoft MimeOLE V6.00.2900.2869");
			msg.addHeader("ReturnReceipt", "1");
			msg.setSentDate(new Date());
			// 不被当作垃圾邮件的关键代码--end
			Transport trans = session.getTransport();
			trans.connect(sendder, pass); // 邮件的账号密码
			trans.sendMessage(msg, msg.getAllRecipients());
			trans.close();
		} catch (AddressException e) {
			LoggerFactory.getLogger(MailUtil.class).error("邮件服务器配置错误", e);
		} catch (NoSuchProviderException e) {
			LoggerFactory.getLogger(MailUtil.class).error("邮件服务器配置错误", e);
		} catch (MessagingException e) {
			LoggerFactory.getLogger(MailUtil.class).error("邮件服务器配置错误", e);
		}
	}
}