/**
 * Company Name : 中贸促信息技术有限责任公司
 * Project Name:investCenterWebsite
 * File Name:MailUtil.java
 * Package Name:ccpit.base.utils.mailUtil
 * Date:2015年11月19日上午11:15:36
 * Copyright (c) 2015, dingwei@ccpit.org All Rights Reserved.
 *
*/

package org.ccpit.base.utils.mailUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
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 javax.mail.internet.MimeUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * ClassName:MailUtil <br/>
 * Function: 邮件发送工具类. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2015年11月19日 上午11:15:36 <br/>
 * @author   dingwei
 * @version  
 * @since    JDK 1.6
 * @see 	 
 */
public class MailUtil {

	private static final Logger log = LoggerFactory.getLogger(MailUtil.class);
	
	public static boolean sendMail(Mail mail){
		
		Properties properties = new Properties();
		properties.setProperty("mail.host", mail.getHost());
		properties.setProperty("mail.transport.protocol", mail.getProtocol());
		properties.setProperty("mail.smtp.auth", "true");
		//使用JavaMail发送邮件的5个步骤
		//1、创建session
		Session session = Session.getInstance(properties);
		//开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
		session.setDebug(true);
		boolean flag = false;
		try {
			//2、通过session得到transport对象
			final Transport transport = session.getTransport();
			//3、连上邮件服务器
			transport.connect(mail.getHost(), mail.getEmailCount(), mail.getEmailPassword());
			//4、创建邮件
			final Message message = createMail(session,mail);
			//5、发送邮件
			new Thread(){
				@Override
				public void run(){
					for(int i=0;i<5;i++){
						try {
							transport.sendMessage(message, message.getAllRecipients());
							transport.close();
							break;
						} catch (MessagingException e) {
							e.printStackTrace();
						}
					}
				}
			}.start();
			flag = true;
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			flag = false;
		} catch (MessagingException e) {
			log.debug("连接邮件服务器失败...");
			flag = false;
			e.printStackTrace();
		}
		return flag;
	}
		
	
	public static MimeMessage createMail(Session session,Mail mail){
		
		MimeMessage mimeMessage = new MimeMessage(session);
		try {
			if(null != mail.getSender()){
				//设置发件人
				mimeMessage.setFrom(new InternetAddress(mail.getSender()));
			}
			if(null != mail.getReceiver()){
				String[] address = mail.getReceiver().split(";");
				InternetAddress[] addresses = new InternetAddress[address.length];
				for(int i=0; i<address.length;i++){
					addresses[i] = new InternetAddress(address[i]);
				}
				//设置收件人 群发
				mimeMessage.setRecipients(Message.RecipientType.TO, addresses);
			}
			if(null != mail.getCopyTo()){
				String[] address = mail.getReceiver().split(";");
				InternetAddress[] addresses = new InternetAddress[address.length];
				for(int i=0; i<address.length;i++){
					addresses[i] = new InternetAddress(address[i]);
				}
				//抄送人 群发
				mimeMessage.setRecipients(Message.RecipientType.CC, addresses);
			}
			//邮件主题
			mimeMessage.setSubject(mail.getMailTitle());
			//创建邮件正文   为了避免邮件正文中文乱码问题，需要使用charset=UTF-8指明字符编码
			MimeBodyPart mimeBodyPart = new MimeBodyPart();
			mimeBodyPart.setContent(mail.getMailMessage(), "text/html;charset=UTF-8");
			Set<MimeBodyPart> mimeBodyPartSet = new HashSet<MimeBodyPart>();
			//创建邮件附件
			if(null != mail.getAffix() && !"".equals(mail.getAffix())){
				//多附件,附件地址之间以";"分隔
				String[] affixs = mail.getAffix().split(";");
				for(int i=0; i<affixs.length;i++){
					File file = new File(affixs[i]);
					MimeBodyPart mbp = new MimeBodyPart();
					DataHandler dh = new DataHandler(new FileDataSource(file));
					mbp.setDataHandler(dh);
					mbp.setFileName(MimeUtility.encodeText(dh.getName()));
					mimeBodyPartSet.add(mbp);
				}
			}
			//创建容器描述数据关系
			MimeMultipart mimeMultipart = new MimeMultipart();
			mimeMultipart.addBodyPart(mimeBodyPart);
			if(null != mimeBodyPartSet && mimeBodyPartSet.size()>0){
				for(MimeBodyPart mbp : mimeBodyPartSet){
					mimeMultipart.addBodyPart(mbp);
				}
			}
			mimeMultipart.setSubType("mixed");
			mimeMessage.setContent(mimeMultipart);
			mimeMessage.saveChanges();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			log.debug("附件转码失败...");
			e.printStackTrace();
		}
		return mimeMessage;
	}
}

