MailServiceImpl.java 8 KB
package com.diligrp.website.service.impl;

import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.diligrp.website.domain.DataDictionary;
import com.diligrp.website.domain.DataDictionaryValue;
import com.diligrp.website.domain.Mail;
import com.diligrp.website.manager.DataDictionaryManager;
import com.diligrp.website.manager.MailManager;
import com.diligrp.website.service.MailService;
import com.diligrp.website.util.dao.BaseQuery;
import com.diligrp.website.util.web.PageTemplate;
import com.diligrp.website.web.interfaces.domain.output.MailResp;
import com.google.common.collect.Maps;
import com.sun.mail.util.MailSSLSocketFactory;

@Component("mailService")
public class MailServiceImpl implements MailService {

	private static final Logger LOG = LoggerFactory.getLogger(MailServiceImpl.class);

	@Resource
	private DataDictionaryManager dataDictionaryManager;

	@Resource
	private MailManager mailManager;

	@Override
	public boolean sendMail(Mail mail) {

		DataDictionary dd = dataDictionaryManager.getDataDictionaryByCode(DIC_EMAIL_CONFIG);

		if (dd == null) {
			LOG.error("数据字典中没有邮件服务器相关配置:" + DIC_EMAIL_CONFIG);
			return false;
		}

		List<DataDictionaryValue> dv = dataDictionaryManager.getDataDictionaryValue(dd.getId());

		if (CollectionUtils.isEmpty(dv)) {
			LOG.error("数据字典中没有找到相应的配置:" + DIC_EMAIL_CONFIG);
			return false;
		}

		Map<String, DataDictionaryValue> dicMap = makeDicDataMap(dv);

		boolean flag = doSendMail(dicMap, mail);

		if (flag) {
			flag = mailManager.saveMail(mail);
		}

		return flag;
	}

	@Override
	public MailResp sendMailByTemplate(Mail mh, String code, Map<String, String> param) {

		MailResp resp = new MailResp();
		DataDictionary ddCfg = dataDictionaryManager.getDataDictionaryByCode(DIC_EMAIL_CONFIG);
		if (ddCfg == null) {
			LOG.error("数据字典中没有邮件服务器相关配置:" + DIC_EMAIL_CONFIG);
			resp.setCode(MailResp.CODE_MAIL_CFG_IS_NOT_EMPTY);
			resp.setMsg("数据字典中没有邮件服务器相关配置:" + DIC_EMAIL_CONFIG);
			return resp;
		}

		List<DataDictionaryValue> dv = dataDictionaryManager.getDataDictionaryValue(ddCfg.getId());

		if (CollectionUtils.isEmpty(dv)) {
			LOG.error("数据字典中没有找到相应的配置:" + DIC_EMAIL_CONFIG);
			LOG.error("数据字典中没有邮件服务器相关配置:" + DIC_EMAIL_CONFIG);
			resp.setCode(MailResp.CODE_MAIL_CFG_IS_NOT_EMPTY);
			resp.setMsg("数据字典中没有邮件服务器相关配置:" + DIC_EMAIL_CONFIG);
			return resp;
		}

		Map<String, DataDictionaryValue> dicMap = makeDicDataMap(dv);

		DataDictionary ddTemplate = dataDictionaryManager.getDataDictionaryByCode(DIC_MAIL_TEMPLATE);
		if (ddTemplate == null) {
			LOG.error("数据字典中没有邮件模板配置:" + DIC_MAIL_TEMPLATE);
			resp.setCode(MailResp.CODE_CAN_NOT_FIND_MAIL_TEMPLATE);
			resp.setMsg("数据字典中没有邮件模板配置:" + DIC_MAIL_TEMPLATE);
			return resp;
		}
		DataDictionaryValue template = dataDictionaryManager.getDataDicValByCode(code, ddTemplate.getId().intValue());
		if (template == null) {
			LOG.error("数据字典中没有邮件模板:" + code);
			resp.setCode(MailResp.CODE_TEMPLATE_IS_NOT_EXISTS);
			resp.setMsg("数据字典中没有邮件模板:" + code);
			return resp;
		}
		String content = template.getRemark();
		if (!StringUtils.isEmpty(content)) {
			content = replaceTemplate(content, param);
		}
		mh.setContent(content);
		if (doSendMail(dicMap, mh)) {
			resp.setCode(MailResp.CODE_SUCCESS);
		} else {
			resp.setCode(MailResp.CODE_FAIL);
		}
		return resp;
	}

	private String replaceTemplate(String content, Map<String, String> param) {
		for (String key : param.keySet()) {
			content = content.replace(key, param.get(key));
		}
		return content;
	}

	private boolean doSendMail(Map<String, DataDictionaryValue> dicMap, Mail mail) {

		String host = dicMap.get(DIC_EMAIL_SMTP_HOST).getName();
		int port = Integer.parseInt(dicMap.get(DIC_EMAIL_SMTP_PORT).getName());
		String from = dicMap.get(DIC_EMAIL_SMTP_ACCOUNT).getName();
		final String username = dicMap.get(DIC_EMAIL_SMTP_ACCOUNT).getName();
		final String password = dicMap.get(DIC_EMAIL_SMTP_PASSWORD).getName();

		Properties props = new Properties();
		Boolean flag = Boolean.valueOf(dicMap.get(EMAIL_SMTP_ENABLESSL).getName());
		if (flag) {
			MailSSLSocketFactory sf;
			try {
				sf = new MailSSLSocketFactory();
			} catch (GeneralSecurityException e) {
				LOG.error("发送邮件失败:" + e.getMessage());
				return false;
			}
			sf.setTrustAllHosts(true);
			// or
			// sf.setTrustedHosts(new String[] { "my-server" });
			props.put("mail.smtp.ssl.enable", "true");
			// also use following for additional safety
			// props.put("mail.smtp.ssl.checkserveridentity", "true");
			props.put("mail.smtp.ssl.socketFactory", sf);
		}

		props.put("mail.smtp.host", host);
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.auth", true);

		mail.setSender(from);

		LOG.info("开始发送邮件发送邮件:调用ip=" + mail.getIp() + ",发送地址:" + mail.getAddressee());
		LOG.info("发送邮件:主题=" + mail.getSubject() + ",发送内容:" + mail.getContent());

		Session session = Session.getDefaultInstance(props, new Authenticator() {

			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		Message message = new MimeMessage(session);

		try {
			BodyPart bodyPart = new MimeBodyPart();
			bodyPart.setContent(mail.getContent(), "text/html;charset=utf-8");

			Multipart multi = new MimeMultipart();
			multi.addBodyPart(bodyPart);

			message.setFrom(new InternetAddress(from));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(mail.getAddressee()));
			message.setSubject(mail.getSubject());
			message.setContent(multi);
			Transport.send(message);
		} catch (Exception e) {
			LOG.error("发送邮件失败! 邮件地址:" + mail.getAddressee(), e);
			return false;
		}
		LOG.info("邮件发送成功!邮件地址:" + mail.getAddressee());
		return true;
	}

	/*
	 * public static void main(String[] args) { DataDictionaryValue host = new
	 * DataDictionaryValue(); host.setName("mail.diligrp.com");
	 * DataDictionaryValue port = new DataDictionaryValue(); port.setName("25");
	 * DataDictionaryValue account = new DataDictionaryValue();
	 * account.setName("system@diligrp.com"); DataDictionaryValue password = new
	 * DataDictionaryValue(); password.setName("g@-GXAWF~Po.t+W"); Map<String,
	 * DataDictionaryValue> dicMap = Maps.newHashMap();
	 * dicMap.put("EMAIL_SMTP_HOST", host); dicMap.put("EMAIL_SMTP_PORT", port);
	 * dicMap.put("EMAIL_SMTP_ACCOUNT", account);
	 * dicMap.put("EMAIL_SMTP_PASSWORD", password); Mail mail = new Mail();
	 * mail.setAddressee("wangzhipeng@diligrp.com"); mail.setSubject("test");
	 * mail.setContent("content abs"); doSendMail(dicMap, mail); }
	 */

	/**
	 * 
	 * 创建数据字典Mp
	 * 
	 * @param dv
	 * @return
	 * @createTime 2014年6月3日 下午1:46:15
	 * @author Wang22
	 */
	private Map<String, DataDictionaryValue> makeDicDataMap(List<DataDictionaryValue> dv) {
		Map<String, DataDictionaryValue> dicMap = Maps.newHashMap();
		for (DataDictionaryValue val : dv) {
			dicMap.put(val.getCode(), val);
		}
		return dicMap;
	}

	@Override
	public PageTemplate queryMail(BaseQuery query) {
		return mailManager.queryMail(query);
	}

}