原博客地址:http://wang3065.iteye.com/blog/1718381
Spring Mail API
Spring Mail API都在org.springframework.mail及其子包org.springframework.mail.javamail中封装。
JavaMailSenderImpl: 邮件发送器,主要提供了邮件发送接口、透明创建Java Mail的MimeMessage、及邮件发送的配置(如:host/port/username/password…)。
MimeMailMessage、MimeMessageHelper:对MimeMessage进行了封装。Spring还提供了一个回调接口MimeMessagePreparator, 用于准备JavaMail的MIME信件.
一、MailUtil类负责发送
/**
* spring发送mail工具
* @author: haleywang,@created on: 2012-9-20
*/
public class MailUtil {
Logger log = Logger.getLogger(MailUtil.class);
private JavaMailSender javaMailSender;
private VelocityEngine velocityEngine; //模板解析
/**
* @param mailBean
* @return
* @throws MessagingException
*/
public boolean send(MailBean mailBean) throws MessagingException {
MimeMessage msg = createMimeMessage(mailBean);
if(msg == null){
return false;
}
this.sendMail(msg, mailBean);
return true;
}
private void sendMail(MimeMessage msg, MailBean mailBean){
javaMailSender.send(msg);
log.info("$$$ Send mail Subject:" + mailBean.getSubject()
+ ", TO:" + arrayToStr(mailBean.getToEmails()) );
}
/*
* 记日记用的
*/
private String arrayToStr(String[] array){
if(array == null || array.length == 0){
return null;
}
StringBuffer sb = new StringBuffer();
for(String str : array){
sb.append(str+" , ") ;
}
return sb.toString();
}
/*
* 根据 mailBean 创建 MimeMessage
*/
private MimeMessage createMimeMessage(MailBean mailBean) throws MessagingException {
if (!checkMailBean(mailBean)) {
return null;
}
String text = getMessage(mailBean);
if(text == null){
log.warn("@@@ warn mail text is null (Thread name="
+ Thread.currentThread().getName() + ") @@@ " + mailBean.getSubject());
return null;
}
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(msg, true, "UTF-8");
//messageHelper.setFrom(mailBean.getFrom());
try {
messageHelper.setFrom(mailBean.getFrom(), mailBean.getFromName());
} catch (UnsupportedEncodingException e) {
log.error(e);
}
messageHelper.setSubject(mailBean.getSubject());
messageHelper.setTo(mailBean.getToEmails());
messageHelper.setText(text, true); // html: true
return msg;
}
/*
* 模板解析
* @param mailBean
* @return
*/
private String getMessage(MailBean mailBean) {
StringWriter writer = null;
try {
writer = new StringWriter();
VelocityContext context = new VelocityContext(mailBean.getData());
velocityEngine.evaluate(context, writer, "", mailBean.getTemplate());
return writer.toString();
} catch (VelocityException e) {
log.error(" VelocityException : " + mailBean.getSubject() + "\n" + e);
} catch (IOException e) {
log.error(" IOException : " + mailBean.getSubject() + "\n" + e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
log.error("###StringWriter close error ... ");
}
}
}
return null;
}
/*
* check 邮件
*/
private boolean checkMailBean(MailBean mailBean){
if (mailBean == null) {
log.warn("@@@ warn mailBean is null (Thread name="
+ Thread.currentThread().getName() + ") ");
return false;
}
if (mailBean.getSubject() == null) {
log.warn("@@@ warn mailBean.getSubject() is null (Thread name="
+ Thread.currentThread().getName() + ") ");
return false;
}
if (mailBean.getToEmails() == null) {
log.warn("@@@ warn mailBean.getToEmails() is null (Thread name="
+ Thread.currentThread().getName() + ") ");
return false;
}
if (mailBean.getTemplate() == null) {
log.warn("@@@ warn mailBean.getTemplate() is null (Thread name="
+ Thread.currentThread().getName() + ") ");
return false;
}
return true;
}
/*===================== setter & getter =======================*/
public void setJavaMailSender(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
}
二、MailBean类封装邮件信息
public class MailBean implements Serializable {
private String from;
private String fromName;
private String[] toEmails;
private String subject;
private Map data ; //邮件数据
private String template; //邮件模板
//省略setter&getter方法
}
四、springMVC.xml中的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- ================2.自动扫描的包名===================== -->
<context:component-scan base-package="com.dr.sm" />
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:mail.properties</value>
</list>
</property>
</bean>
<import resource="classpath:springMVC-mail.xml"/>
</beans>
五、springMVC-mail.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- 邮件发送器 163 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="defaultEncoding" value="UTF-8"></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
</props>
</property>
</bean>
<!-- 邮件发送器 gmail
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="defaultEncoding" value="UTF-8"></property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
<prop key="mail.smtp.port">465</prop>
<prop key="mail.smtp.socketFactory.port">465</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
</props>
</property>
</bean>
-->
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
</bean>
<bean id="mailUtil" class="com.dr.sm.mail.MailUtil">
<property name="javaMailSender" ref="mailSender"></property>
<property name="velocityEngine" ref="velocityEngine"></property>
</bean>
</beans>
六、mail.properties属性文件
mail.from=jfhlge900@163.com
mail.host=smtp.163.com
mail.password=********
mail.smtp.auth=true
mail.smtp.timeout=25000
mail.username=jfh
#mail.from=jfhlge900@163.com
#mail.host=smtp.gmail.com
#mail.password=********
#mail.smtp.auth=true
#mail.smtp.timeout=25000
#mail.username=jfhlge900@gmail.com
七、测试
@ContextConfiguration("classpath:springMVC.xml")
public class MailServiceTest extends AbstractJUnit4SpringContextTests {
@Resource
private MailUtil mailUtil;
@Test
public void testSendMail() {
//创建邮件
MailBean mailBean = new MailBean();
mailBean.setFrom("jfhlge900@163.com");
mailBean.setSubject("hello world");
mailBean.setToEmails(new String[]{"jfhlge900@gmail.com"});
mailBean.setTemplate("hello ${userName} !<a href='www.baidu.com' >baidu</a>");
Map map = new HashMap();
map.put("userName", "hello mail");
mailBean.setData(map);
//发送邮件
try {
mailUtil.send(mailBean);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}