Spring - Java/J2EE Application Framework 应用框架 第 17 章 使用Spring邮件抽象层发送Email
第?17?章?使用Spring郵件抽象層發送Email
17.1.?簡介
Spring提供了一個發送電子郵件的高級抽象層,它向用戶屏蔽了底層郵件系統的一些細節,同時負責低層次的代表客戶端的資源處理。
17.2.?Spring郵件抽象結構
Spring郵件抽象層的主要包為org.springframework.mail。它包括了發送電子郵件的主要接口MailSender和 封裝了簡單郵件的屬性如from,?to,cc,?subject,?text的值對象叫做SimpleMailMessage。 一個以MailException為root的checked Exception繼承樹,它們提供了對底層郵件系統異常的高級別抽象。 請參考JavaDocs來得到關于郵件異常層次的更多的信息。
為了使用JavaMail中的一些特色如MIME類型的消息,Spring也提供了一個MailSender的子接口, 名為org.springframework.mail.javamail.JavaMailSender,同時也提供了一個對JavaMail的MIME類型的消息分塊的回調interface, 名為org.springframework.mail.javamail.MimeMessagePreparator
MailSender:
public interface MailSender {/*** Send the given simple mail message.* @param simpleMessage message to send* @throws MailException in case of message, authentication, or send errors*/public void send(SimpleMailMessage simpleMessage) throws MailException;/*** Send the given array of simple mail messages in batch.* @param simpleMessages messages to send* @throws MailException in case of message, authentication, or send errors*/public void send(SimpleMailMessage[] simpleMessages) throws MailException;}JavaMailSender:
public interface JavaMailSender extends MailSender {/*** Create a new JavaMail MimeMessage for the underlying JavaMail Session* of this sender. Needs to be called to create MimeMessage instances* that can be prepared by the client and passed to send(MimeMessage).* @return the new MimeMessage instance* @see #send(MimeMessage)* @see #send(MimeMessage[])*/public MimeMessage createMimeMessage();/*** Send the given JavaMail MIME message.* The message needs to have been created with createMimeMessage.* @param mimeMessage message to send* @throws MailException in case of message, authentication, or send errors* @see #createMimeMessage*/public void send(MimeMessage mimeMessage) throws MailException;/*** Send the given array of JavaMail MIME messages in batch.* The messages need to have been created with createMimeMessage.* @param mimeMessages messages to send* @throws MailException in case of message, authentication, or send errors* @see #createMimeMessage*/public void send(MimeMessage[] mimeMessages) throws MailException;/*** Send the JavaMail MIME message prepared by the given MimeMessagePreparator.* Alternative way to prepare MimeMessage instances, instead of createMimeMessage* and send(MimeMessage) calls. Takes care of proper exception conversion.* @param mimeMessagePreparator the preparator to use* @throws MailException in case of message, authentication, or send errors*/public void send(MimeMessagePreparator mimeMessagePreparator) throws MailException;/*** Send the JavaMail MIME messages prepared by the given MimeMessagePreparators.* Alternative way to prepare MimeMessage instances, instead of createMimeMessage* and send(MimeMessage[]) calls. Takes care of proper exception conversion.* @param mimeMessagePreparators the preparator to use* @throws MailException in case of message, authentication, or send errors*/public void send(MimeMessagePreparator[] mimeMessagePreparators) throws MailException;}MimeMessagePreparator:
public interface MimeMessagePreparator {/*** Prepare the given new MimeMessage instance.* @param mimeMessage the message to prepare* @throws MessagingException passing any exceptions thrown by MimeMessage* methods through for automatic conversion to the MailException hierarchy*/void prepare(MimeMessage mimeMessage) throws MessagingException;}17.3.?使用Spring郵件抽象
讓我們來假設有一個業務接口名為OrderManager
public interface OrderManager {void placeOrder(Order order); }同時有一個use case為:需要生成帶有訂單號的email信息,并向客戶發送該訂單。 為了這個目的我們會使用MailSender和SimpleMailMessage。
請注意,通常情況下,我們在業務代碼中使用接口而讓Spring ioc容器負責組裝我們需要的合作者。
這里為OrderManager的一個實現
import org.springframework.mail.MailException; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage;public class OrderManagerImpl implements OrderManager {private MailSender mailSender;private SimpleMailMessage message;public void setMailSender(MailSender mailSender) {this.mailSender = mailSender;}public void setMessage(SimpleMailMessage message) {this.message = message;}public void placeOrder(Order order) {//... * Do the businness calculations....//... * Call the collaborators to persist the order//Create a threadsafe "sandbox" of the messageSimpleMailMessage msg = new SimpleMailMessage(this.message);msg.setTo(order.getCustomer().getEmailAddress());msg.setText("Dear "+ order.getCustomer().getFirstName()+ order.getCustomer().getLastName()+ ", thank you for placing order. Your order number is "+ order.getOrderNumber());try{mailSender.send(msg);}catch(MailException ex) {//log it and go onSystem.err.println(ex.getMessage()); }} }上面的代碼的bean的定義應該是這樣的:
<bean id="mailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl"><property name="host"><value>mail.mycompany.com</value></property> </bean><bean id="mailMessage"class="org.springframework.mail.SimpleMailMessage"><property name="from"><value>customerservice@mycompany.com</value></property><property name="subject"><value>Your order</value></property> </bean><bean id="orderManager"class="com.mycompany.businessapp.support.OrderManagerImpl"><property name="mailSender"><ref bean="mailSender"/></property><property name="message"><ref bean="mailMessage"/></property> </bean>下面是OrderManager的實現,使用了MimeMessagePreparator回調接口。 請注意這里的mailSender屬性類型為JavaMailSender,這樣做是為了能夠使用JavaMail的MimeMessage:
import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMessage; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessagePreparator;public class OrderManagerImpl implements OrderManager {private JavaMailSender mailSender;public void setMailSender(JavaMailSender mailSender) {this.mailSender = mailSender;}public void placeOrder(final Order order) {//... * Do the businness calculations....//... * Call the collaborators to persist the orderMimeMessagePreparator preparator = new MimeMessagePreparator() {public void prepare(MimeMessage mimeMessage) throws MessagingException {mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(order.getCustomer().getEmailAddress()));mimeMessage.setFrom(new InternetAddress("mail@mycompany.com"));mimeMessage.setText("Dear "+ order.getCustomer().getFirstName()+ order.getCustomer().getLastName()+ ", thank you for placing order. Your order number is "+ order.getOrderNumber());}};try{mailSender.send(preparator);}catch(MailException ex) {//log it and go onSystem.err.println(ex.getMessage()); }} }如果你想使用JavaMail MimeMessage以獲得全部的能力,只需要你指尖輕觸鍵盤即可使用MimeMessagePreparator。
請注意這部分郵件代碼是一個橫切關注點,是一個可以重構至一個定制的SpringAOP advice的完美候選者, 這樣就可以不費力的應用到目標對象OrderManager上來。關于這一點請看AOP章節。
17.3.1.?可插拔的MailSender實現
Spring提供兩種MailSender的實現:標準的JavaMail實現和在http://servlets.com/cos?(com.oreilly.servlet)里的Jason Hunter's?MailMessage類之上的實現。請參考JavaDocs以得到進一步的信息。
from:?http://docs.huihoo.com/spring/zh-cn/mail.html
總結
以上是生活随笔為你收集整理的Spring - Java/J2EE Application Framework 应用框架 第 17 章 使用Spring邮件抽象层发送Email的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring - Java/J2EE A
- 下一篇: Spring - Java/J2EE A