歡迎您光臨本站 註冊首頁

用Spring讓Java Mail支持簡化郵件發送

←手機掃碼閱讀     火星人 @ 2014-03-12 , reply:0
  

閑來無事,翻看《Spring in Action》,發現Spring集成了對JAVA Mail的支持,有點小激動的看了一遍,嗯,話說真的簡單了很多。

Spring的郵件發送的核心是MailSender介面,在Spring3.0中提供了一個實現類JavaMailSenderImpl,這個類是發送郵件的核心類。可以通過在配置文件中配置使用,當然也可以自己硬編碼到代碼中(方便起見,下面的演示代碼都是硬編碼到代碼中,省得配置麻煩)。

Spring提供的郵件發送不僅支持簡單郵件的發送、添加附件,而且還可以使用velocity模板控制頁面樣式(應該也支持freemarker)。

首先對加入相應Spring jar包和Java Mail 的jar包。

我們首先得聲明一個MailSender對象,因為MailSender對象只有兩個重載的send(...)方法,顯得有些簡陋,我們建議選用JavaMailSender介面,或者乾脆直接使用實現類,JavaMailSenderImpl。筆者是使用的JavaMailSenderImpl對象,功能豐富。

聲明JavaMailSenderImpl對象,並在構造函數中初始化(當然也可以使用IoC容器初始化):

  1. public class SpringMailSender {  
  2. // Spring的郵件工具類,實現了MailSender和JavaMailSender介面  
  3. private JavaMailSenderImpl mailSender;  
  4. public SpringMailSender() {  
  5. // 初始化JavaMailSenderImpl,當然推薦在spring配置文件中配置,這裡是為了簡單  
  6. mailSender = new JavaMailSenderImpl();  
  7. // 設置參數  
  8. mailSender.setHost("smtp.qq.com");  
  9. mailSender.setUsername("786553789@qq.com");  
  10. mailSender.setPassword("556WULI779");  
  11. ... 

得到了MailSender對象之後,就可以發送郵件了,下面是示例代碼,沒有封裝,僅供參考。

1、發送簡單郵件

  1. /**  
  2. * 簡單郵件發送  
  3. *  
  4. */ 
  5. public void simpleSend() {  
  6. // 構建簡單郵件對象,見名知意  
  7. SimpleMailMessage smm = new SimpleMailMessage();  
  8. // 設定郵件參數  
  9. smm.setFrom(mailSender.getUsername());  
  10. smm.setTo("mosaic@126.com");  
  11. smm.setSubject("Hello world");  
  12. smm.setText("Hello world via spring mail sender");  
  13. // 發送郵件  
  14. mailSender.send(smm);  

2、發送帶附件的郵件

  1. /**  
  2. * 帶附件的郵件發送  
  3. *  
  4. * @throws MessagingException  
  5. */ 
  6. public void attachedSend() throws MessagingException {  
  7. //使用JavaMail的MimeMessage,支付更加複雜的郵件格式和內容  
  8. MimeMessage msg = mailSender.createMimeMessage();  
  9. //創建MimeMessageHelper對象,處理MimeMessage的輔助類  
  10. MimeMessageHelper helper = new MimeMessageHelper(msg, true);  
  11. //使用輔助類MimeMessage設定參數  
  12. helper.setFrom(mailSender.getUsername());  
  13. helper.setTo("mosaic@126.com");  
  14. helper.setSubject("Hello Attachment");  
  15. helper.setText("This is a mail with attachment");  
  16. //載入文件資源,作為附件  
  17. ClassPathResource file = new ClassPathResource(  
  18. "Chrysanthemum.jpg");  
  19. //加入附件  
  20. helper.addAttachment("attachment.jpg", file);  
  21. //發送郵件  
  22. mailSender.send(msg);  

3、發送富文本郵件

  1. /**發送富文本郵件  
  2. * @throws MessagingException  
  3. */ 
  4. public void richContentSend() throws MessagingException {  
  5. MimeMessage msg = mailSender.createMimeMessage();  
  6. MimeMessageHelper helper = new MimeMessageHelper(msg, true);  
  7. helper.setFrom(mailSender.getUsername());  
  8. helper.setTo("mosaic@126.com");  
  9. helper.setSubject("Rich content mail");  
  10. //第二個參數true,表示text的內容為html,然後注意<img/>標籤,src='cid:file',
  11. 'cid'是contentId的縮寫,'file'是一個標記,
  12. 需要在後面的代碼中調用MimeMessageHelper的addInline方法替代成文件  
  13. helper.setText(  
  14. "<body><p>Hello Html Email</p><img src='cid:file'/></body>",  
  15. true);  
  16. FileSystemResource file = new FileSystemResource(  
  17. "C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg");  
  18. helper.addInline("file", file);  
  19. mailSender.send(msg);  

4、使用Velocity模板確定郵件風格

使用Velocity模板,需要Velocity的jar包,可以在官方網站下載,並加入ClassPath,然後需要聲明一個VelocityEngine對象,具體的參考下面代碼,這是筆者第一次使用Velocity,不甚了解,言多有失,望見諒。

聲明一個VelocityEngine對象,並在構造函數中初始化(IoC is optional)

  1. ...  
  2. private VelocityEngine velocityEngine;  
  3. public SpringMailSender() {  
  4. ...  
  5. // Velocity的參數,通過VelocityEngineFactoryBean創建VelocityEngine,也是推薦在配置文件中配置的  
  6. Properties props = System.getProperties();  
  7. props.put("resource.loader""class");  
  8. props  
  9. .put("class.resource.loader.class",  
  10.  "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");  
  11. VelocityEngineFactoryBean v = new VelocityEngineFactoryBean();  
  12. v.setVelocityProperties(props);  
  13. try {  
  14. velocityEngine = v.createVelocityEngine();  
  15. catch (VelocityException e) {  
  16. e.printStackTrace();  
  17. catch (IOException e) {  
  18. e.printStackTrace();  
  19. }  

簡單的Velocity模板文件(index.vm):

  1. <html> 
  2. <head> 
  3. <style type="text/css"> 
  4. h4{  
  5. color:red;  
  6. background:#efefef;  
  7. }  
  8. </style> 
  9. </head> 
  10. <body> 
  11. <h4>${user} </h4> 
  12. <p><p> 
  13. <i>${content}</i> 
  14. </body> 
  15. </html> 

開起來貌似很容易理解,只是普通的Html文件,使用了一些${placeholder}作為佔位符。

Java要做的,就是載入模板,並將相應的值插入到佔位符當中。

  1. /**  
  2. * 使用Velocity模板發送郵件  
  3. *  
  4. * @throws MessagingException  
  5. */ 
  6. public void templateSend() throws MessagingException {  
  7. // 聲明Map對象,並填入用來填充模板文件的鍵值對  
  8. Map<String, String> model = new HashMap<String, String>();  
  9. model.put("user""MZULE");  
  10. model.put("content""Hello");  
  11. // Spring提供的VelocityEngineUtils將模板進行數據填充,並轉換成普通的String對象  
  12. String emailText = VelocityEngineUtils.mergeTemplateIntoString(  
  13. velocityEngine, "index.vm", model);  
  14. // 和上面一樣的發送郵件的工作  
  15. MimeMessage msg = mailSender.createMimeMessage();  
  16. MimeMessageHelper helper = new MimeMessageHelper(msg, true);  
  17. helper.setFrom(mailSender.getUsername());  
  18. helper.setTo("mosaic@126.com");  
  19. helper.setSubject("Rich content mail");  
  20. helper.setText(emailText, true);  
  21.  mailSender.send(msg);  

Spring可謂是大大簡化了郵件的發送步驟,雖然我們自己封裝可能實現起來並不複雜,但是,有現成的有何必要重新造輪子呢?(當然造輪子可以學到很多)

原文鏈接:http://www.cnblogs.com/codeplus/archive/2011/11/03/2232893.html

 



[火星人 ] 用Spring讓Java Mail支持簡化郵件發送已經有1051次圍觀

http://coctec.com/docs/program/show-post-71454.html