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


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

 

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

 

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

 

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

 

1、創建郵件發送器

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

Java代碼 復制代碼  收藏代碼
  1. JavaMailSenderImpl mailSender = new JavaMailSenderImpl();   
  2. mailSender.setHost("smtp.qq.com");   
  3. mailSender.setUsername("mosaic@qq.com");   
  4. mailSender.setPassword("asterisks");  
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.qq.com");
mailSender.setUsername("mosaic@qq.com");
mailSender.setPassword("asterisks");

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

以上主機為郵箱服務商的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("mosaic@126.com");   
  5. smm.setSubject("Hello world");   
  6. smm.setText("Hello world via spring mail sender");   
  7. // 發送郵件   
  8. mailSender.send(smm);  
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");
// 發送郵件
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("mosaic@126.com");   
  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);  
//使用JavaMail的MimeMessage,支付更加復雜的郵件格式和內容
MimeMessage msg = mailSender.createMimeMessage();
//創建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);
// 發送郵件
mailSender.send(smm);

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

Java代碼 復制代碼  收藏代碼
  1. FileSystemResource file = new FileSystemResource("C:\\Users\\image1.jpg");   
  2. helper.addInline("file", file);  
FileSystemResource file = new FileSystemResource("C:\\Users\\image1.jpg");
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.  
 void	send(MimeMessage mimeMessage) 
          Send the given JavaMail MIME message.
 void	send(MimeMessage[] mimeMessages) 
          Send the given array of JavaMail MIME messages in batch.
 void	send(MimeMessagePreparator mimeMessagePreparator) 
          Send the JavaMail MIME message prepared by the given MimeMessagePreparator.
 void	send(MimeMessagePreparator[] mimeMessagePreparators) 
          Send the JavaMail MIME messages prepared by the given MimeMessagePreparators.
 void	send(SimpleMailMessage simpleMessage) 
          Send the given simple mail message.
 void	send(SimpleMailMessage[] simpleMessages) 
          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.  
setText(String text, boolean html) 
          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);  
//第二個參數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\\image1.jpg");
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="BACKGROUND-COLOR: #ffffff; WHITE-SPACE: normal"> </SPAN>  
<html>
	<head>
	</head>
	<body>
		<div>${user} </div>
		<div>${content}</div>
	</body>
</html> 

為了方便省略了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);  
// Velocity的參數,通過VelocityEngineFactoryBean創建VelocityEngine,也是推薦在配置文件中配置的
Properties properties = System.getProperties();
properties.put("resource.loader", "class");
properties.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngineFactoryBean v = new VelocityEngineFactoryBean();
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);  
// 聲明Map對象,並填入用來填充模板文件的鍵值對
Map<String, String> model = new HashMap<String, String>();
model.put("user", "ooo");
model.put("content", "nihao");
// Spring提供的VelocityEngineUtils將模板進行數據填充,並轉換成普通的String對象
String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "index.vm", model);

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

 

5.4 設置郵件內容,同4

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

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

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM