java 利用spring JavaMailSenderImpl發送郵件,支持普通文本、附件、html、velocity模板

原文鏈接

本文主要介紹利用JavaMailSenderImpl發送郵件。首先介紹了發送一般郵件,然後介紹了發送富文本(html)郵件以velocity爲模板發送郵件。

 

郵件發送分爲爲三步:創建郵件發送器編寫郵件發送郵件

 

springJavaMailSenderImpl提供了強大的郵件發送功能,可發送普通文本郵件、帶附件郵件、html格式郵件、帶圖片郵件、設置發送內容編碼格式、設置發送人的顯示名稱。

 

下面就進行介紹,示例代碼中很多都是字符串硬編碼,實際使用時推薦使用spring的配置文件進行配置。

 

1、創建郵件發送器

首先定義JavaMailSenderImpl對象,並對其進行smtp相關信息設置,相當於我們自己的郵箱,如下:

Java代碼  收藏代碼
  1. JavaMailSenderImpl mailSender = new JavaMailSenderImpl();  
  2. mailSender.setHost("smtp.qq.com");  
  3. mailSender.setUsername("[email protected]");  
  4. mailSender.setPassword("xxxxxx");  

當然更好的方法是使用配置文件進行配置,這裏只是進行介紹,忽略硬編碼先。

以上主機爲郵箱服務商的smtp地址,用戶名、密碼爲用戶自己的郵箱。除以上外還可以設置

setPort(int port) 、setProtocol(String protocol) 等,可暫時不考慮。

這樣我們便類似創建好了一個郵件發送器

 

2、 開始寫郵件,編寫郵件內容

JavaMailSenderImpl支持MimeMessagesSimpleMailMessages

MimeMessages爲複雜郵件模板,支持文本、附件、html、圖片等。

SimpleMailMessages實現了MimeMessageHelper,爲普通郵件模板,支持文本。

下面先以SimpleMailMessages爲例進行介紹

Java代碼  收藏代碼
  1. SimpleMailMessage smm = new SimpleMailMessage();  
  2. // 設定郵件參數  
  3. smm.setFrom(mailSender.getUsername());  
  4. smm.setTo("[email protected]");  
  5. smm.setSubject("Hello world");  
  6. smm.setText("Hello world via spring mail sender");  
  7. // 發送郵件  
  8. mailSender.send(smm);  

如此,我們便完成了一個簡單郵件的編寫,對於複雜郵件,編寫及發送如下

Java代碼  收藏代碼
  1. //使用JavaMail的MimeMessage,支付更加複雜的郵件格式和內容  
  2. MimeMessage msg = mailSender.createMimeMessage();  
  3. //創建MimeMessageHelper對象,處理MimeMessage的輔助類  
  4. MimeMessageHelper helper = new MimeMessageHelper(msg, true);  
  5. //使用輔助類MimeMessage設定參數  
  6. helper.setFrom(mailSender.getUsername());  
  7. helper.setTo("[email protected]");  
  8. helper.setSubject("Hello Attachment");  
  9. helper.setText("This is a mail with attachment");  
  10. //加載文件資源,作爲附件  
  11. ClassPathResource file = new ClassPathResource("Chrysanthemum.jpg");  
  12. //加入附件  
  13. helper.addAttachment("attachment.jpg", file);  
  14. // 發送郵件  
  15. mailSender.send(smm);  

其中MimeMessageHelper爲的輔助類MimeMessages。以上包含了以資源文件爲附件進行發送。對於普通文件發送方式如下:

Java代碼  收藏代碼
  1. FileSystemResource file = new FileSystemResource("C:\\Users\\image1.jpg");  
  2. helper.addInline("file", file);  

 

3、發送郵件

2中已經包含了發送的代碼,只需使用JavaMailSenderImpl的send接口即可。支持類型爲

Java代碼  收藏代碼
  1. void    send(MimeMessage mimeMessage)   
  2.          Send the given JavaMail MIME message.  
  3. void    send(MimeMessage[] mimeMessages)   
  4.          Send the given array of JavaMail MIME messages in batch.  
  5. void    send(MimeMessagePreparator mimeMessagePreparator)   
  6.          Send the JavaMail MIME message prepared by the given MimeMessagePreparator.  
  7. void    send(MimeMessagePreparator[] mimeMessagePreparators)   
  8.          Send the JavaMail MIME messages prepared by the given MimeMessagePreparators.  
  9. void    send(SimpleMailMessage simpleMessage)   
  10.          Send the given simple mail message.  
  11. void    send(SimpleMailMessage[] simpleMessages)   
  12.          Send the given array of simple mail messages in batch.  

 

下面介紹下怎麼發送富文本文件以及以velocity爲模板發送郵件。

4、發送html文件

只需要在MimeMessageHelper setText時將是否是html設爲true即可。setText介紹如下:

Xml代碼  收藏代碼
  1. setText(String text, boolean html)   
  2.           Set the given text directly as content in non-multipart mode or as default body part in multipart mode.  

示例代碼(包括附件)如下:

Java代碼  收藏代碼
  1. //第二個參數true,表示text的內容爲html  
  2. //注意<img/>標籤,src='cid:file','cid'是contentId的縮寫,'file'是一個標記,需要在後面的代碼中調用MimeMessageHelper的addInline方法替代成文件  
  3. helper.setText("<body><p>Hello Html Email</p><img src='cid:file'/></body>"true);  
  4. FileSystemResource file = new FileSystemResource("C:\\Users\\image1.jpg");  
  5. helper.addInline("file", file);  

 

5、以velocity爲模板發送郵件

使用Velocity模板,需要Velocity的jar包,可以在官方網站下載,並加入ClassPath。

以velocity爲模板發送郵件的原理如下:

a 類似web編程,將velocity作爲前端,在Java中設置vm中需要顯示的變量值

b 使用VelocityEngineUtilsmergeTemplateIntoString函數將vm內容轉換爲文本

c 同4的發送html郵件一樣發送郵件

所以最重要的過程將是將vm的內容轉換爲string,即設置郵件內容,其他同上面並無差異

 

5.1 新建vm文件,命名爲index.vm

Java代碼  收藏代碼
  1. <html>  
  2.     <head>  
  3.     </head>  
  4.     <body>  
  5.         <div>${user} </div>  
  6.         <div>${content}</div>  
  7.     </body>  
  8. </html><span style="white-space: normal; background-color: #ffffff;"> </span>  

爲了方便省略了html頭定義。
其中${user} 爲Velocity的語法,相當於一個變量,在java程序中可以設置這個變量的值在前端顯示。

 

5.2 創建VelocityEngineFactoryBean對象,並設置屬性

Java代碼  收藏代碼
  1. // Velocity的參數,通過VelocityEngineFactoryBean創建VelocityEngine,也是推薦在配置文件中配置的  
  2. Properties properties = System.getProperties();  
  3. properties.put("resource.loader""class");  
  4. properties.put("class.resource.loader.class""org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");  
  5. VelocityEngineFactoryBean v = new VelocityEngineFactoryBean();  
  6. v.setVelocityProperties(properties);  

 

5.3 轉換vm內容爲普通String

Java代碼  收藏代碼
  1. // 聲明Map對象,並填入用來填充模板文件的鍵值對  
  2. Map<String, String> model = new HashMap<String, String>();  
  3. model.put("user""ooo");  
  4. model.put("content""nihao");  
  5. // Spring提供的VelocityEngineUtils將模板進行數據填充,並轉換成普通的String對象  
  6. String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "index.vm", model);  

這樣我們便將vm中的變量值填充好,並且將內容轉換爲了string

 

5.4 設置郵件內容,同4

Java代碼  收藏代碼
  1. helper.setText(emailText, true);  

其他內容同上面的1、2、3過程。

 

注意:vm文件格式需要與郵件編碼一致否則會出現亂碼

 

參考:

http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/mail/javamail/JavaMailSenderImpl.html

http://www.cnblogs.com/codeplus/archive/2011/11/03/2232893.html

http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/mail/javamail/

http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/ui/velocity/VelocityEngineUtils.html


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章