用Spring讓Java Mail支持簡化郵件發(fā)送
閑來無事,翻看《Spring in Action》,發(fā)現Spring集成了對JAVA Mail的支持,有點小激動的看了一遍,嗯,話說真的簡單了很多。
Spring的郵件發(fā)送的核心是MailSender接口,在Spring3.0中提供了一個實現類JavaMailSenderImpl,這個類是發(fā)送郵件的核心類??梢酝ㄟ^在配置文件中配置使用,當然也可以自己硬編碼到代碼中(方便起見,下面的演示代碼都是硬編碼到代碼中,省得配置麻煩)。
Spring提供的郵件發(fā)送不僅支持簡單郵件的發(fā)送、添加附件,而且還可以使用velocity模板控制頁面樣式(應該也支持freemarker)。
首先對加入相應Spring jar包和Java Mail 的jar包。
我們首先得聲明一個MailSender對象,因為MailSender對象只有兩個重載的send(...)方法,顯得有些簡陋,我們建議選用JavaMailSender接口,或者干脆直接使用實現類,JavaMailSenderImpl。筆者是使用的JavaMailSenderImpl對象,功能豐富。
聲明JavaMailSenderImpl對象,并在構造函數中初始化(當然也可以使用IoC容器初始化):
- public class SpringMailSender {
 - // Spring的郵件工具類,實現了MailSender和JavaMailSender接口
 - private JavaMailSenderImpl mailSender;
 - public SpringMailSender() {
 - // 初始化JavaMailSenderImpl,當然推薦在spring配置文件中配置,這里是為了簡單
 - mailSender = new JavaMailSenderImpl();
 - // 設置參數
 - mailSender.setHost("smtp.qq.com");
 - mailSender.setUsername("786553789@qq.com");
 - mailSender.setPassword("556WULI779");
 - ...
 
得到了MailSender對象之后,就可以發(fā)送郵件了,下面是示例代碼,沒有封裝,僅供參考。
1、發(fā)送簡單郵件
- /**
 - * 簡單郵件發(fā)送
 - *
 - */
 - public void simpleSend() {
 - // 構建簡單郵件對象,見名知意
 - SimpleMailMessage smm = new SimpleMailMessage();
 - // 設定郵件參數
 - smm.setFrom(mailSender.getUsername());
 - smm.setTo("mosaic@126.com");
 - smm.setSubject("Hello world");
 - smm.setText("Hello world via spring mail sender");
 - // 發(fā)送郵件
 - mailSender.send(smm);
 - }
 
2、發(fā)送帶附件的郵件
- /**
 - * 帶附件的郵件發(fā)送
 - *
 - * @throws MessagingException
 - */
 - public void attachedSend() throws MessagingException {
 - //使用JavaMail的MimeMessage,支付更加復雜的郵件格式和內容
 - MimeMessage msg = mailSender.createMimeMessage();
 - //創(chuàng)建MimeMessageHelper對象,處理MimeMessage的輔助類
 - MimeMessageHelper helper = new MimeMessageHelper(msg, true);
 - //使用輔助類MimeMessage設定參數
 - helper.setFrom(mailSender.getUsername());
 - helper.setTo("mosaic@126.com");
 - helper.setSubject("Hello Attachment");
 - helper.setText("This is a mail with attachment");
 - //加載文件資源,作為附件
 - ClassPathResource file = new ClassPathResource(
 - "Chrysanthemum.jpg");
 - //加入附件
 - helper.addAttachment("attachment.jpg", file);
 - //發(fā)送郵件
 - mailSender.send(msg);
 - }
 
3、發(fā)送富文本郵件
- /**發(fā)送富文本郵件
 - * @throws MessagingException
 - */
 - public void richContentSend() throws MessagingException {
 - MimeMessage msg = mailSender.createMimeMessage();
 - MimeMessageHelper helper = new MimeMessageHelper(msg, true);
 - helper.setFrom(mailSender.getUsername());
 - helper.setTo("mosaic@126.com");
 - helper.setSubject("Rich content mail");
 - //第二個參數true,表示text的內容為html,然后注意<img/>標簽,src='cid:file',
 - 'cid'是contentId的縮寫,'file'是一個標記,
 - 需要在后面的代碼中調用MimeMessageHelper的addInline方法替代成文件
 - helper.setText(
 - "<body><p>Hello Html Email</p><img src='cid:file'/></body>",
 - true);
 - FileSystemResource file = new FileSystemResource(
 - "C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg");
 - helper.addInline("file", file);
 - mailSender.send(msg);
 - }
 
4、使用Velocity模板確定郵件風格
使用Velocity模板,需要Velocity的jar包,可以在官方網站下載,并加入ClassPath,然后需要聲明一個VelocityEngine對象,具體的參考下面代碼,這是筆者***次使用Velocity,不甚了解,言多有失,望見諒。
聲明一個VelocityEngine對象,并在構造函數中初始化(IoC is optional)
- ...
 - private VelocityEngine velocityEngine;
 - public SpringMailSender() {
 - ...
 - // Velocity的參數,通過VelocityEngineFactoryBean創(chuàng)建VelocityEngine,也是推薦在配置文件中配置的
 - Properties props = System.getProperties();
 - props.put("resource.loader", "class");
 - props
 - .put("class.resource.loader.class",
 - "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
 - VelocityEngineFactoryBean v = new VelocityEngineFactoryBean();
 - v.setVelocityProperties(props);
 - try {
 - velocityEngine = v.createVelocityEngine();
 - } catch (VelocityException e) {
 - e.printStackTrace();
 - } catch (IOException e) {
 - e.printStackTrace();
 - }
 - }
 
簡單的Velocity模板文件(index.vm):
- <html>
 - <head>
 - <style type="text/css">
 - h4{
 - color:red;
 - background:#efefef;
 - }
 - </style>
 - </head>
 - <body>
 - <h4>${user} </h4>
 - <p><p>
 - <i>${content}</i>
 - </body>
 - </html>
 
開起來貌似很容易理解,只是普通的Html文件,使用了一些${placeholder}作為占位符。
Java要做的,就是加載模板,并將相應的值插入到占位符當中。
- /**
 - * 使用Velocity模板發(fā)送郵件
 - *
 - * @throws MessagingException
 - */
 - public void templateSend() throws MessagingException {
 - // 聲明Map對象,并填入用來填充模板文件的鍵值對
 - Map<String, String> model = new HashMap<String, String>();
 - model.put("user", "MZULE");
 - model.put("content", "Hello");
 - // Spring提供的VelocityEngineUtils將模板進行數據填充,并轉換成普通的String對象
 - String emailText = VelocityEngineUtils.mergeTemplateIntoString(
 - velocityEngine, "index.vm", model);
 - // 和上面一樣的發(fā)送郵件的工作
 - MimeMessage msg = mailSender.createMimeMessage();
 - MimeMessageHelper helper = new MimeMessageHelper(msg, true);
 - helper.setFrom(mailSender.getUsername());
 - helper.setTo("mosaic@126.com");
 - helper.setSubject("Rich content mail");
 - helper.setText(emailText, true);
 - mailSender.send(msg);
 - }
 
Spring可謂是大大簡化了郵件的發(fā)送步驟,雖然我們自己封裝可能實現起來并不復雜,但是,有現成的有何必要重新造輪子呢?(當然造輪子可以學到很多)
原文鏈接:http://www.cnblogs.com/codeplus/archive/2011/11/03/2232893.html
【編輯推薦】















 
 
 

 
 
 
 