使用Spring的JAVA Mail支持簡化郵件發送功能

這篇文章主要爲大家詳細介紹了使用Spring的JAVA Mail支持簡化郵件發送功能,具有一定的參考價值,感興趣的小夥伴們可以參考一下

閒來無事,翻看《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容器初始化):

public class SpringMailSender
 {
 
 //
 Spring的郵件工具類,實現了MailSender和JavaMailSender接口
 private JavaMailSenderImpl
 mailSender;
  
 public SpringMailSender()
 {
 //
 初始化JavaMailSenderImpl,當然推薦在spring配置文件中配置,這裏是爲了簡單
 mailSender
 = new JavaMailSenderImpl();
 //
 設置參數
 mailSender.setHost("smtp.qq.com");
 mailSender.setUsername("[email protected]");
 mailSender.setPassword("asterisks");
 ...

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

1、發送簡單郵件

/**
 *
 簡單郵件發送
 *
 */
public void simpleSend()
 {
 //
 構建簡單郵件對象,見名知意
 SimpleMailMessage
 smm = new SimpleMailMessage();
 //
 設定郵件參數
 smm.setFrom(mailSender.getUsername());
 smm.setTo("[email protected]");
 smm.setSubject("Hello
 world");
 smm.setText("Hello
 world via spring mail sender");
 //
 發送郵件
 mailSender.send(smm);
}

2、發送帶附件的郵件

/**
 *
 帶附件的郵件發送
 *
 *
 @throws MessagingException
 */
public void attachedSend()
throws MessagingException
 {
 //使用JavaMail的MimeMessage,支付更加複雜的郵件格式和內容
 MimeMessage
 msg = mailSender.createMimeMessage();
 //創建MimeMessageHelper對象,處理MimeMessage的輔助類
 MimeMessageHelper
 helper = new MimeMessageHelper(msg,
true);
 //使用輔助類MimeMessage設定參數
 helper.setFrom(mailSender.getUsername());
 helper.setTo("[email protected]");
 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(msg);
}

3、發送富文本郵件

/**發送富文本郵件
 *
 @throws MessagingException
 */
public void richContentSend()
throws MessagingException
 {
 MimeMessage
 msg = mailSender.createMimeMessage();
 
 MimeMessageHelper
 helper = new MimeMessageHelper(msg,
true);
 
 helper.setFrom(mailSender.getUsername());
 helper.setTo("[email protected]");
 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創建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模板發送郵件
 *
 *
 @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);
 //
 和上面一樣的發送郵件的工作
 MimeMessage
 msg = mailSender.createMimeMessage();
 MimeMessageHelper
 helper = new MimeMessageHelper(msg, true);
 helper.setFrom(mailSender.getUsername());
 helper.setTo("[email protected]");
 helper.setSubject("Rich
 content mail");
 helper.setText(emailText,
 true);
 
 mailSender.send(msg);
}

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

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