前言
Spring对Java的邮件发送提供了很好的支持,提供了超级简单的API,大大简化了Java邮件发送功能的开发。
Spring对Email的支持是基于JavaMail API开发的,所以,我们在使用Spring开发Java邮件发送功能时,需要引入javax.mail-api和其实现类mail包,如下:
<dependency> <groupId>javax.mailgroupId> <artifactId>javax.mail-apiartifactId> <version>1.5.5version> dependency> <dependency> <groupId>javax.mailgroupId> <artifactId>mailartifactId> <version>1.4.7version> dependency>
另外,如果打算使用freemarker作为邮件主题的模板的话,还需引入freemarker:
<dependency> <groupId>org.freemarkergroupId> <artifactId>freemarkerartifactId> <version>2.3.23version> dependency>
最后,添加其它依赖spring-context-support、spring-context等;
Bean配置——JavaMailSenderImpl
Spring提供了两个基础接口用于发送邮件:
MailSender:发送简单的邮件信息,提供基本功能,如‘from’, ’to’, ’cc’, ’bcc’, ’subject’ 以及其它邮件属性。
JavaMailSender:对MailSender进行扩展,提供专业的JavaMail特性,如对MIME消息的支持。
JavaMailSenderImpl是JavaMailSender接口的实现,一般我们都会使用它来进行邮件发送,如下是javaMailSender bean的配置:
比较简单,就不细说了,注意下端口的配置,密码是邮件账号的密码,我这里改成了XXXXXX。
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.qq.com">property> <property name="port" value="25">property> <property name="username" value="[email protected]">property> <property name="password" value="XXXXXX">property> <property name="defaultEncoding" value="UTF-8">property> <property name="javaMailProperties"> <props> <prop key="mail.transport.protocol">smtpprop> <prop key="mail.smtp.auth">trueprop> props> property> bean>
Bean配置——FreeMarkerConfigurationFactoryBean
因为我们使用了freemarker作为邮件主体的模板,所以这里对freeMarker做了下配置
<bean id="freeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean"> <property name="templateLoaderPath" value="classpath:emailtemplates" /> bean>
另外,我们使用的freeMarker模板如下:
<html> <body> <h3>User name: ${user.name} has been deleted.h3> <h6>Detail:h6> <div> <p>user id : ${user.id}.p> <p>user address : ${user.address}.p> div> <span>Sent using FreeMarker Templatespan> body> html>
编写邮件发送Service
主要工作落在组装MIME消息,使用Freemarker模板生成邮件主体,另外我们还给邮件添加了一张图片作为附件,
package cn.edu.hdu.webbf.service.mail.impl; import java.util.HashMap; import java.util.Map; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import cn.edu.hdu.webbf.common.log.Logger; import cn.edu.hdu.webbf.service.mail.IMailService; import freemarker.template.Configuration; @Service("mailService") public class MailServiceImpl implements IMailService { protected Logger logger = Logger.getLogger(this.getClass()); @Autowired JavaMailSender mailSender; @Autowired Configuration freemarkerConfiguration; @Override public void sendEmail(Object obj) { MimeMessagePreparator preparator = getMessagePreparator(obj); try { mailSender.send(preparator); logger.info("mail send sesuccss."); } catch (MailException ex) { logger.error(ex.getMessage(), ex); } } private MimeMessagePreparator getMessagePreparator(final Object obj) { MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom("[email protected]"); helper.setTo("[email protected]"); helper.setSubject("mail test."); Mapmodel = new HashMap (); model.put("user", obj); String text = geFreeMarkerTemplateContent(model);//Use Freemarker helper.setText(text, true); helper.addAttachment("userdel.png", new ClassPathResource("imgs/userdel.png")); } }; return preparator; } public String geFreeMarkerTemplateContent(Map model) { StringBuffer content = new StringBuffer(); try { content.append(FreeMarkerTemplateUtils.processTemplateIntoString( freemarkerConfiguration.getTemplate("fm_userDeleted.txt"), model)); return content.toString(); } catch (Exception e) { logger.error("Exception occured while processing fmtemplate:" + e.getMessage(), e); } return ""; } }
Controller调用
删除用户的时候,发送一封通知邮件,说明那个用户被删除了。
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "application/json; charset=utf-8") public ResponseEntitydeleteUser(@PathVariable Long id) { User user = userService.findById(id); if (user == null) { return new ResponseEntity (HttpStatus.NOT_FOUND); } userService.deleteUser(id); mailService.sendEmail(user); return new ResponseEntity (HttpStatus.NO_CONTENT); }
结果验证
访问用户管理,并删除一个用户,然后查看邮件,结果如下:
源码参考
https://github.com/peterchenhdu/webbf
参考资料
http://websystique.com/spring/spring-4-email-integration-tutorial/
http://websystique.com/spring/spring-4-email-using-velocity-freemaker-template-library/