package com.zhiwei.manage.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.zhiwei.manage.bean.Messages;

/**
 * 邮件发送工具类
 * @author shenjinzhu
 */
@Component
public class SendMailUtil {

	public static String emailAccount = "shenjinzhu999@163.com";// "ccxerisk@sina.com";//"yuhongbo@ccxe.com.cn";
	public static String emailPassword = "sjz123";
	public static String emailSMTPHost = "smtp.163.com";
	public static String receiveMailAccount = "****@**.com";

	/**
	 * 指数用于发送邮件
	 * @param mail
	 * @param url
	 */
	public static void sendMessage(String mail,Messages msg) {
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.host", "smtp.163.com");
		props.setProperty("mail.smtp.auth", "true");
		Session session = Session.getInstance(props);
		session.setDebug(false); 
		MimeMessage message;
		try {
			message = createMimeMessage(session, "shenjinzhu999@163.com", mail,msg);
			Transport transport = session.getTransport();
			transport.connect("shenjinzhu999@163.com", "shenjinzhu123");
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Messages m=new Messages();
		m.setTitle("title");
		m.setContent("content");
		sendMessage("shenjinzhu999@163.com", m);
	}
	/**
	 * 只包含附件，指数专用
	 * 
	 * @param session
	 * @param sendMail
	 * @param receiveMail
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail,Messages msg)
			throws Exception {
		MimeMessage message = new MimeMessage(session);
		String str = msg.getDate();
		message.setFrom(new InternetAddress(sendMail, "数据管理预警", "UTF-8"));
		message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "UTF-8"));
		message.setSubject(str+msg.getTitle(), "UTF-8");
		BodyPart messageBodyPart = new MimeBodyPart();
		String content = msg.getContent();
		messageBodyPart.setText(content);
		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(messageBodyPart);
		message.setContent(multipart);
		message.setSentDate(new Date());
		message.saveChanges();
		return message;
	}

}
