使用Spring提供的MailSender异步发送文本邮件
在工程中经常有发送邮件的任务,如果使用JavaMail来发送邮件,用到的代码较多,过程和细节也相对复杂,而使用Spring的MailSender能相对简单方便些,这样使程序员能更快捷的完成邮件发送任务。下面请看示例代码:
注意在执行代码前,请确认已经将activation.jar,commons-logging-1.0.4.jar,mail.jar和spring.jar载入工程。
四.使用示例package com.heyang.util;import java.util.List;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.heyang.tool.mailsender.BaseMailSender;import com.heyang.tool.mailsender.MailSenderImpl;/** * 异步邮件发送实用类(使用Spring的邮件发送形式) * @author: 何杨(heyang78@gmail.com) * @date: 2008-8-6-下午02:43:22 */ public final class MailUtil { /** * 发送邮件 * @param emailAddr:收信人邮件地址 * @param mailTitle:邮件标题 * @param mailConcept:邮件内容 */ public static void sendMail(final String emailAddr, final String mailTitle, final String mailConcept) { Runnable thread=new Runnable(){ public void run(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); BaseMailSender sender=(MailSenderImpl)context.getBean("mailSender"); sender.sendMail(emailAddr, mailTitle, mailConcept); } }; new Thread(thread).start(); } /** * 向系统维护者发送邮件 * @param mailTitle * @param mailConcept */ public static void sendMailToSupporters(final String mailTitle, final String mailConcept){ Runnable thread=new Runnable(){ public void run(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); SupportTeam supportTeam=(SupportTeam)context.getBean("supportTeam"); BaseMailSender sender=(MailSenderImpl)context.getBean("mailSender"); List<String> mails=supportTeam.getSupporterEmails(); for(String mailAddr:mails){ sender.sendMail(mailAddr, mailTitle, mailConcept); } } }; new Thread(thread).start(); } /** * 测试邮件发送 * @param args */ public static void main(String[] args){ MailUtil.sendMailToSupporters("title_spring", "concept_spring"); } }