Spring對Java的郵件發送提供了很好的支持,提供了超級簡單的API,大大簡化了Java郵件發送功能的開發。
Spring對Email的支持是基於JavaMail API開發的,所以,我們在使用Spring開發Java郵件發送功能時,需要引入javax.mail-api和其實現類mail包,如下:
<!-- JavaMail --> <dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
另外,如果打算使用freemarker作為郵件主題的模板的話,還需引入freemarker:
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
最後,添加其它依賴spring-context-support、spring-context等;
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">smtp</prop> <prop key="mail.smtp.auth">true</prop> <!-- true for Gamil <prop key="mail.smtp.starttls.enable">false</prop> <prop key="mail.debug">true</prop>--> </props> </property> </bean>
因為我們使用了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 Template</span> </body> </html>
主要工作落在組裝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."); Map<String, Object> model = new HashMap<String, Object>(); 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<String, Object> 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 ""; } }
刪除用戶的時候,發送一封通知郵件,說明那個用戶被刪除了。
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "application/json; charset=utf-8") public ResponseEntity<User> deleteUser(@PathVariable Long id) { User user = userService.findById(id); if (user == null) { return new ResponseEntity<User>(HttpStatus.NOT_FOUND); } userService.deleteUser(id); mailService.sendEmail(user); return new ResponseEntity<User>(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/