MailSendService

来自ling
跳转至: 导航搜索
package com.deloitte.tr.mail.service;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.util.StringUtils;

import com.deloitte.tr.common.LogAction;
import com.deloitte.tr.common.LogCategories;
import com.deloitte.tr.common.LogModule;
import com.deloitte.tr.log.service.LogService;
import com.deloitte.tr.mail.Email;
import com.deloitte.tr.message.model.EmailMessage;
import com.ling2.core.commons.utils.SpringUtil;
import com.ling2.core.context.utils.ContextUtils;
import com.ling2.core.dao.IDao;

@Component
public class MailSendService {
	@Resource
	LogService logService;

	@Resource
	private VelocityEngine velocityEngine;

	/**
	 * 使方法异步执行
	 * 
	 * @param email
	 * @param mailSender
	 */
	@Async
	public void sendMailAsync(Email email, JavaMailSender mailSender) {
		execSendMailImmediately(email, mailSender);
	}

	/**
	 * 使方法能带事务
	 * 
	 * @param email
	 * @param mailSender
	 */
	@Transactional
	public void execSendMailImmediately(Email email, JavaMailSender mailSender) {
		/********************* bo.wang begin 将所有发送的邮件记录在案 ********************/
		EmailMessage emailMessage = new EmailMessage();
		emailMessage.setCcs(buildArrayToString(email.getCcs()));
		emailMessage.setContent(email.getText());
		emailMessage.setOperator(ContextUtils.getCurrentUser() == null ? null
				: ContextUtils.getCurrentUser().getUsername());
		emailMessage.setRecipients(buildArrayToString(email.getRecipients()));
		emailMessage.setSend(false);
		emailMessage.setSendDate(new Date());
		emailMessage.setTitle(email.getSubject());

		IDao dao = SpringUtil.getBean("messageDao");
		dao.save(emailMessage);
		/********************* bo.wang end *********************/
		boolean sucess = false;
		try {
			MimeMessage mailMessage = buildMimeMessage(email, mailSender);
			mailSender.send(mailMessage);
			sucess = true;
			logService.info(email.getSubject() + "发送邮件成功",
					LogCategories.normalEvent.getText(),
					LogAction.insert.getText(), LogModule.mail.getText(), "",
					email.getSubject());
		} catch (Exception e) {
			emailMessage.setInfo(e.getMessage());
			// throw new MailSendException("邮件发送失败", e);
			// e.printStackTrace();
			logService.info(email.getSubject() + "发送邮件失败",
					LogCategories.normalEvent.getText(),
					LogAction.insert.getText(), LogModule.mail.getText(), "",
					e.getMessage());
		} finally {
//			System.out.println(2);
			emailMessage.setSend(sucess);
			dao.update(emailMessage);
		}
	}

	private MimeMessage buildMimeMessage(Email email, JavaMailSender mailSender)
			throws MessagingException, UnsupportedEncodingException {
		MimeMessage mailMessage = mailSender.createMimeMessage();
		MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,
				true, "utf-8");
		if (StringUtils.hasText(email.getNick())) {
			messageHelper.setFrom(new InternetAddress(new StringBuilder(email
					.getNick()).append("<").append(email.getSender())
					.append(">").toString()));
		} else {
			messageHelper.setFrom(new InternetAddress(email.getSender()));
		}
		// messageHelper.setTo(email.getRecipients().toArray(
		// new String[email.getRecipients().size()]));
		messageHelper.setTo("jasonbwang@deloitte.com.cn");
		// zhangboqi++ 2016-08-02 添加要cc的邮箱
		if (email.getCcs() != null && email.getCcs().size() > 0) {
			messageHelper.setBcc(email.getCcs().toArray(
					new String[email.getCcs().size()]));
		}

		messageHelper.setSubject(email.getSubject());
		messageHelper.setText(email.getText(), true);
		for (Iterator<Entry<String, File>> iterator = email.getAttachmentMap()
				.entrySet().iterator(); iterator.hasNext();) {
			Entry<String, File> entry = iterator.next();
			messageHelper.addAttachment(MimeUtility.encodeWord(entry.getKey()),
					entry.getValue());
		}
		for (Iterator<Entry<String, File>> iterator = email.getInlineMap()
				.entrySet().iterator(); iterator.hasNext();) {
			Entry<String, File> entry = iterator.next();
			messageHelper.addInline(MimeUtility.encodeWord(entry.getKey()),
					entry.getValue());
		}

		return mailMessage;
	}

	private String _buildMessage(String templateLocation,
			Map<String, Object> model) {
		return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
				templateLocation, "utf-8", model);
	}

	private String buildMessage(String templateLocation,
			Map<String, Object> model) {
		return _buildMessage(templateLocation, model);
	}

	private static String buildArrayToString(List<String> contents) {
		String result = "";
		for (String content : contents) {
			result = com.ling2.core.commons.utils.StringUtils.join(result,
					content, ",");
		}
		return result;
	}
}