欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java集成spring异步发送邮件

程序员文章站 2024-01-07 14:28:46
...
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("goujia@goujiawang.com");
			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);
	}
}

 

<beans:bean class="com.goujia.ges.common.helper.MailSender">
    	<beans:property name="mailSender" ref="javaMailSender"></beans:property>
    </beans:bean>
    
     <beans:bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
       <beans:property name="host" value="smtp.qq.com" />
       <beans:property name="port" value="25" />
       <beans:property name="username" value="" />
       <beans:property name="password" value="" />
       <!-- SMTP服务器验证 -->  
       <beans:property name="javaMailProperties">  
           <beans:props>  
               	<!-- 验证身份 -->  
           		<beans:prop key="mail.smtp.auth">true</beans:prop>
            	<beans:prop key="mail.smtp.timeout">25000</beans:prop> 
          </beans:props>  
       </beans:property>  
   </beans:bean> 

 

相关标签: javamail

上一篇:

下一篇: