MailUtils.java 7.13 KB
Newer Older
manxiaoqiang committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
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.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);
		// 发送给多个人
		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);
		// 发送给多个人
		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);
		// 发送给多个人
		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();
		}
		
			
	}
}