java集成spring异步发送邮件

阅读更多
package com.goujia.ges.common.helper;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.goujia.ges.common.util.SSLUtils;

/**
 * 邮件发送器
 * 
 * @author xieshangzhen
 * @date 2015年9月28日
 * @version 1.0
 */
public class MailSender {

	private static final Logger logger = LoggerFactory
			.getLogger(MailSender.class);

	private JavaMailSender mailSender;

	private Executor executor = Executors.newFixedThreadPool(10);

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	/**
	 * 邮件发送同步
	 * @param to 接收方
	 * @param subject 主题
	 * @param content 内容
	 * @throws Exception 
	 */
	public void sendMail(final String to, final String subject,
			final String content) throws Exception {

			//SSLUtils.ignoreSsl();
		try {
			MimeMessage message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message, true,
					"utf-8");
			helper.setTo(to);
			helper.setFrom("[email protected]");
			helper.setSubject(subject);
			helper.setText(content, true);
			mailSender.send(message);
			logger.info("mail already send");
		} catch (MessagingException e) {
			logger.error("generate mail fialure");
			e.printStackTrace();
		}
	}

	/**
	 * 邮件发送异步
	 * @param to 接收方
	 * @param subject 主题
	 * @param content 内容
	 */
	public void sendMailAsync(final String to, final String subject,
			final String content) {
		Runnable task = new Runnable() {

			@Override
			public void run() {
				try {
					sendMail(to, subject, content);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		executor.execute(task);
	}
}

 


    	
    
    
       
       
       
       
       
         
         
             
               	  
           		true
            	25000 
            
         
    

 

你可能感兴趣的:(javamail)