package util;

import common.model.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class MailUtils {
	public static final String CONTENT_TYPE = Constant.mailContentType;
	public static final String FROM_EMAIL_ADDRESS = Constant.mailUsername;
	/**
	 * 简单的发邮件方式 邮件内容只有标题和邮件内容 支持多个用户批量发送
	 * 
	 * @param subject
	 *            邮件标题
	 * @param contents
	 *            邮件内容
	 * @param userEmailAddress
	 *            收入人的邮件地址 为List形式
	 * @throws Exception
	 */
	public static void sendSimpleEmail(String subject, String contents,	List<String> userEmailAddress)	throws Exception {
		
		SimpleEmail email = new SimpleEmail();
		email.setHostName(Constant.mailHost);
		email.setAuthentication(FROM_EMAIL_ADDRESS,Constant.mailPassword);

		if(!Boolean.getBoolean(Constant.mailprod)){
			//测试环境
			userEmailAddress = new ArrayList<>();
			List<String> users = Arrays.asList(Constant.mailtestUser.split(","));
			for(String u :users){
				userEmailAddress.add(u+"@reyun.com");
			}
		}

		// 发送给多个人
		for (int i = 0; i < userEmailAddress.size(); i++) {
			email.addTo(userEmailAddress.get(i), userEmailAddress.get(i));
		}

		email.setFrom(FROM_EMAIL_ADDRESS, FROM_EMAIL_ADDRESS);
		email.setSubject(subject);
		email.setContent(contents, CONTENT_TYPE);
		email.send();
	}

	/**
	 * 发送带附件的邮件方式 邮件内容有标题和邮件内容和附件，附件可以是本地机器上的文本，也可以是web上的一个URL 文件，
	 * 当为web上的一个URL文件时，此方法可以将WEB中的URL文件先下载到本地，再发送给收入用户
	 * 
	 * @param subject
	 *            邮件标题
	 * @param contents
	 *            邮件内容
	 * @param userEmailAddress
	 *            收入人的邮件地址 为List形式
	 * @param multiPaths
	 *            附件地址 为数组形式
	 * @throws Exception
	 * @throws Exception
	 */

	public static void sendMultiPartEmail(String subject, String contents, List<String> userEmailAddress, String[] multiPaths) throws Exception {
		// MimeUtility.encodeText(filename); 测试中文乱码用的
		// EmailAttachment attachment = new EmailAttachment();
		// attachment.setPath("D:/aaa.ppt");
		// attachment.setDisposition(EmailAttachment.ATTACHMENT);
		// attachment.setDescription("Picture of John");
		List list = new ArrayList();
		// EmailAttachment [] attachmentArray = new
		// EmailAttachment[multiPaths.length];
		for (int j = 0; j < multiPaths.length; j++) {
			EmailAttachment attachment = new EmailAttachment();
			if (multiPaths[j].indexOf("http") == -1) // 判断当前这个文件路径是否在本地
														// 如果是：setPath 否则
														// setURL;
			{
				attachment.setPath(multiPaths[j]);
			} else {
				attachment.setURL(new URL(multiPaths[j]));
			}
			attachment.setDisposition(EmailAttachment.ATTACHMENT);
			attachment.setDescription("");
			list.add(attachment);
		}
		// 发送邮件信息
		MultiPartEmail email = new MultiPartEmail();
		email.setHostName(Constant.mailHost);
		email.setAuthentication(Constant.mailUsername,Constant.mailPassword);

		if(!Boolean.getBoolean(Constant.mailprod)){
			//测试环境
			userEmailAddress = new ArrayList<>();
			List<String> users = Arrays.asList(Constant.mailtestUser.split(","));
			for(String u :users){
				userEmailAddress.add(u+"@reyun.com");
			}
		}


		// 发送给多个人
		for (int i = 0; i < userEmailAddress.size(); i++) {
			email.addTo(userEmailAddress.get(i), userEmailAddress.get(i));
		}
		email.setFrom(FROM_EMAIL_ADDRESS, FROM_EMAIL_ADDRESS);
		email.setSubject("The picture");
		email.setMsg(contents); // 注意这个不要使用setContent这个方法 setMsg不会出现乱码
		for (int a = 0; a < list.size(); a++) // 添加多个附件
		{
			email.attach((EmailAttachment) list.get(a));
		}
		// email.attach(attachment);
		email.send();
	}

	/**
	 * 发送Html格式的邮件
	 * 
	 * @param subject
	 *            邮件标题
	 * @param contents
	 *            邮件内容
	 * @param userEmailAddress
	 *            接收用户的邮箱地址
	 * @param fromEmailAddress
	 *            发送人的邮箱地址
	 * 
	 * @throws Exception
	 */
	public static void sendHtmlEmail(String subject, String contents, List<String> userEmailAddress)
			throws Exception {
		
		HtmlEmail email = new HtmlEmail();
		email.setHostName(Constant.mailHost);
		email.setAuthentication(Constant.mailUsername,Constant.mailPassword);

		if(!Boolean.getBoolean(Constant.mailprod)){
			//测试环境
			userEmailAddress = new ArrayList<>();
			List<String> users = Arrays.asList(Constant.mailtestUser.split(","));
			for(String u :users){
				userEmailAddress.add(u+"@reyun.com");
			}
		}

		// 发送给多个人
		for (int i = 0; i < userEmailAddress.size(); i++) {
			email.addTo(userEmailAddress.get(i), userEmailAddress.get(i));
		}
		email.setFrom(FROM_EMAIL_ADDRESS, FROM_EMAIL_ADDRESS);
		email.setSubject(subject);
		email.setCharset("UTF-8");
		email.setHtmlMsg(contents);
		email.setTextMsg(contents);
		email.send();
	}

	/**
	 * 统一的发送邮件的方法 调用时一定要实例化EmailBean对象
	 * 
	 * @throws Exception
	 * 
	 */
	public static void sendEmail(Email email) throws Exception {
		if (email.isHaveMultPaths()) {
			sendMultiPartEmail(email.getSubject(), email.getContents(), email.getUserEmailAddress(), email.getMultiPaths());
		} else {
			sendSimpleEmail(email.getSubject(), email.getContents(), email.getUserEmailAddress());
		}
	}

	public static boolean checkEmail(String email) {
		if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
			return false;
		}

		String host = "";
		String hostName = email.split("@")[1];
		Record[] result = null;
		SMTPClient client = new SMTPClient();

		try {
			// 查找MX记录
			Lookup lookup = new Lookup(hostName, Type.MX);
			lookup.run();
			if (lookup.getResult() != Lookup.SUCCESSFUL) {
				return false;
			} else {
				result = lookup.getAnswers();
			}

			// 连接到邮箱服务器
			for (int i = 0; i < result.length; i++) {
				host = result[i].getAdditionalName().toString();
				client.connect(host);
				if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
					client.disconnect();
					continue;
				} else {
					break;
				}
			}
			//以下2项自己填写快速的，有效的邮箱
			client.login("163.com");
			client.setSender("sxgkwei@163.com");
			client.addRecipient(email);
			if (250 == client.getReplyCode()) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				client.disconnect();
			} catch (IOException e) {
			}
		}
		return false;
	}

	public static void main(String[] args) {

		Email email = new Email();
		List<String> mailList = new ArrayList<String>();
		mailList.add("zhangxiaoyan@reyun.com");
		email.setSubject("mail test");
		email.setContents("what's the fuck mail");
		email.setUserEmailAddress(mailList);
		
		StringBuffer content = new StringBuffer();
		content.append("Company: test").append("<br>");
		content.append("Email: test@reyun.com").append("<br>");
		content.append("Name: test").append("<br>");
		content.append("Phone: test").append("<br>");
		content.append("手机归属地：test").append("<br>");
		content.append("IP归属地：test").append("<br>");
		content.append("微信: test").append("<br>");
		content.append("同意请点击--><a href=\"https://www.baidu.com\">https://www.baidu.com</a>");
		try {
			sendHtmlEmail("mail test", content.toString(), mailList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
			
	}
}
