spring-email官方翻譯

  • 2019 年 10 月 30 日
  • 筆記

官方地址:https://docs.spring.io/spring/docs/5.0.0.M5/spring-framework-reference/html/mail.html

Email

Introduction

Library dependencies The following JAR needs to be on the classpath of your application in order to use the Spring Framework』s email library. The JavaMail library This library is freely available on the web — for example, in Maven Central as com.sun.mail:javax.mail. 依賴包 為了使用Spring框架的email包,你的程式需要應用下列包。 JavaMail包 這個Jar包在網上可以免費獲得——比如,在Maven Central中是com.sun.mail:javax.mail

The Spring Framework provides a helpful utility library for sending email that shields the user from the specifics of the underlying mailing system and is responsible for low level resource handling on behalf of the client.

The org.springframework.mail package is the root level package for the Spring Framework』s email support. The central interface for sending emails is the MailSender interface; a simple value object encapsulating the properties of a simple mail such as from and to (plus many others) is the SimpleMailMessage class. This package also contains a hierarchy of checked exceptions which provide a higher level of abstraction over the lower level mail system exceptions with the root exception being MailException. Please refer to the javadocs for more information on the rich mail exception hierarchy.

The org.springframework.mail.javamail.JavaMailSender interface adds specialized JavaMail features such as MIME message support to the MailSender interface (from which it inherits). JavaMailSender also provides a callback interface for preparing a 『MimeMessage』, called org.springframework.mail.javamail.MimeMessagePreparator.

Spring框架提供一個對發送電子郵件有用的工具,對用戶掩蓋郵件系統底層邏輯,代表客戶端負責低級資源處理。 org.springframework.mail包在spring框架電子郵件支援的root級別包。發郵件最重要的介面是MailSender;一個簡單的值對象封裝成一個簡單的郵件屬性,比如send個to(加上其他許多)是SimpleMailMessage 類。這個包還包含一個效驗異常等級,它提供一個高等級的抽象root異常在其他低等級的郵箱系統異常之上,這個異常是MailException。請參考javadocs來了解更多關於郵件異常等級的資訊。 org.springframework.mail.javamail.JavaMailSender介面為MailSender介面(從中繼承)添加了專門的JavaMail功能,如MIME(多用途的網際郵件擴充協議)消息支援。JavaMailSender 還提供一個回調介面來準備MimeMessage, org.springframework.mail.javamail.MimeMessagePreparator。

Usage

Let』s assume there is a business interface called OrderManager:

假設有一個名叫OrderManager的業務介面

public interface OrderManager {        void placeOrder(Order order);    }

Let us also assume that there is a requirement stating that an email message with an order number needs to be generated and sent to a customer placing the relevant order.

讓我們假設有一個需求,指出需要生成帶有訂單號的電子郵件消息並發送給發出相關訂單的客戶。

Basic MailSender and SimpleMailMessage usage

基本的MailSender和SimpleMailMessage用法

import org.springframework.mail.MailException;  import org.springframework.mail.MailSender;  import org.springframework.mail.SimpleMailMessage;    public class SimpleOrderManager implements OrderManager {        private MailSender mailSender;      private SimpleMailMessage templateMessage;        public void setMailSender(MailSender mailSender) {          this.mailSender = mailSender;      }        public void setTemplateMessage(SimpleMailMessage templateMessage) {          this.templateMessage = templateMessage;      }        public void placeOrder(Order order) {            // Do the business calculations...            // Call the collaborators to persist the order...            // Create a thread safe "copy" of the template message and customize it          SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);          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{              this.mailSender.send(msg);          }          catch(MailException ex) {              // simply log it and go on...              System.err.println(ex.getMessage());          }      }  }

Find below the bean definitions for the above code:

查找下面的程式碼的bean定義

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">    <property name="host" value="mail.mycompany.com"/>  </bean>    <!-- this is a template message that we can pre-load with default state -->  <bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">    <property name="from" value="[email protected]"/>    <property name="subject" value="Your order"/>  </bean>    <bean id="orderManager" class="com.mycompany.businessapp.support.SimpleOrderManager">    <property name="mailSender" ref="mailSender"/>    <property name="templateMessage" ref="templateMessage"/>  </bean>

Using the JavaMailSender and the MimeMessagePreparator

使用JavaMailSender和MimeMessagePreparator

Here is another implementation of OrderManager using the MimeMessagePreparator callback interface. Please note in this case that the mailSender property is of type JavaMailSender so that we are able to use the JavaMail MimeMessage class:

這是使用MimeMessagePreparator回調介面的OrderManager的另一個實現類。請注意,在這種情況下,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 SimpleOrderManager implements OrderManager {        private JavaMailSender mailSender;        public void setMailSender(JavaMailSender mailSender) {          this.mailSender = mailSender;      }        public void placeOrder(final Order order) {            // Do the business calculations...            // Call the collaborators to persist the order...            MimeMessagePreparator preparator = new MimeMessagePreparator() {                public void prepare(MimeMessage mimeMessage) throws Exception {                    mimeMessage.setRecipient(Message.RecipientType.TO,                          new InternetAddress(order.getCustomer().getEmailAddress()));                  mimeMessage.setFrom(new InternetAddress("[email protected]"));                  mimeMessage.setText(                      "Dear " + order.getCustomer().getFirstName() + " "                          + order.getCustomer().getLastName()                          + ", thank you for placing order. Your order number is "                          + order.getOrderNumber());              }          };          try {              this.mailSender.send(preparator);          }          catch (MailException ex) {              // simply log it and go on...              System.err.println(ex.getMessage());          }      }  }

Using the JavaMail MimeMessageHelper

使用MimeMessageHelper

A class that comes in pretty handy when dealing with JavaMail messages is the org.springframework.mail.javamail.MimeMessageHelper class, which shields you from having to use the verbose JavaMail API. Using the MimeMessageHelper it is pretty easy to create a MimeMessage:

處理JavaMail資訊非常方便的一個類是org.springframework.mail.javamail.MimeMessageHelper,這使您不用使用詳細的JavaMail API。使用MimeMessageHelper創建一個MimeMessage十分簡單。

MimeMessageHelper可以是構造郵件對象更加簡單,使用MimeMessageHelper構造郵件程式碼。

// of course you would use DI in any real-world cases  JavaMailSenderImpl sender = new JavaMailSenderImpl();  sender.setHost("mail.host.com");    MimeMessage message = sender.createMimeMessage();  MimeMessageHelper helper = new MimeMessageHelper(message);  helper.setTo("[email protected]");  helper.setText("Thank you for ordering!");    sender.send(message);

Sending attachments and inline resources

發送附件和在線資源

Multipart email messages allow for both attachments and inline resources. Examples of inline resources would be images or a stylesheet you want to use in your message, but that you don』t want displayed as an attachment.

大部分郵件資訊允許附件和內聯資源。內聯資源的例子是,比如你要在郵件中使用圖片和樣式,但是你不想以顯示為附件。

Attachments

附件

The following example shows you how to use the MimeMessageHelper to send an email along with a single JPEG image attachment.

下面的例子像你展示如何使用MimeMessageHelper去發送一篇郵件以及單個JPEG圖片附件。

JavaMailSenderImpl sender = new JavaMailSenderImpl();  sender.setHost("mail.host.com");    MimeMessage message = sender.createMimeMessage();    // use the true flag to indicate you need a multipart message  MimeMessageHelper helper = new MimeMessageHelper(message, true);  helper.setTo("[email protected]");    helper.setText("Check out this image!");    // let's attach the infamous windows Sample file (this time copied to c:/)  FileSystemResource file = new FileSystemResource(new File("c:/Sample.jpg"));  helper.addAttachment("CoolImage.jpg", file);    sender.send(message);

Inline resources

內聯資源

The following example shows you how to use the MimeMessageHelper to send an email along with an inline image.

下面的例子向你展示如何使用MimeMessageHelper去發送郵件以及一個內聯圖片。

JavaMailSenderImpl sender = new JavaMailSenderImpl();  sender.setHost("mail.host.com");    MimeMessage message = sender.createMimeMessage();    // use the true flag to indicate you need a multipart message  MimeMessageHelper helper = new MimeMessageHelper(message, true);  helper.setTo("[email protected]");    // use the true flag to indicate the text included is HTML  helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);    // let's include the infamous windows Sample file (this time copied to c:/)  FileSystemResource res = new FileSystemResource(new File("c:/Sample.jpg"));  helper.addInline("identifier1234", res);    sender.send(message);

NOTICE: Inline resources are added to the mime message using the specified Content-ID ( identifier1234 in the above example). The order in which you are adding the text and the resource are very important. Be sure to first add the text and after that the resources. If you are doing it the other way around, it won』t work!

注意:內聯資源被添加在mime資訊中使用規定Content-ID(上面的例子是identifier1234)。你添加text和資源的順序是很重要的。正確的是先添加text再添加資源。如果你靠其他方式去做它,它不會工作!

Creating email content using a templating library

使用郵件內容模板

The code in the previous examples explicitly created the content of the email message, using methods calls such as message.setText(..). This is fine for simple cases, and it is okay in the context of the aforementioned examples, where the intent was to show you the very basics of the API.

In your typical enterprise application though, you are not going to create the content of your emails using the above approach for a number of reasons.

  • Creating HTML-based email content in Java code is tedious and error prone
  • There is no clear separation between display logic and business logic
  • Changing the display structure of the email content requires writing Java code, recompiling, redeploying…

Typically the approach taken to address these issues is to use a template library such as FreeMarker to define the display structure of email content. This leaves your code tasked only with creating the data that is to be rendered in the email template and sending the email. It is definitely a best practice for when the content of your emails becomes even moderately complex, and with the Spring Framework』s support classes for FreeMarker becomes quite easy to do.

在前面例子的程式碼中明確的通過調用比如message.setText(..)的方法創建email資訊內容。這對簡單的例子是適用的,他對前述例子中的上下文也是ok的,它的意圖是向我們展示API的基礎知識。 在你的典型的企業級應用中,你不是去使用上面的例子去創建你的email郵件內容,有下列幾種原因。

  • 創建基於HTML的郵件內容使用java程式碼是枯燥的和易錯的。
  • 顯示邏輯和業務邏輯沒有分開。
  • 改變郵件內容的顯示結構需要寫java程式碼,重新編譯,重新部署…

spring-email支援velocity模板來構建郵件模板。通常的做法是把address這些主題使用模版庫例如FreeMarker去在郵件內容的顯示結構定義。這些離開你程式碼的任務只需要創建發送郵件模版數據並發送郵件。當你的郵件內容變得相當複雜時,這無疑是最好的做法,而且Spring框架對FreeMarker的支援類很容易去做。

模板示例

# in the com/foo/package  <html>  <body>  <h3>Hi ${user.userName}, welcome to the Chipping Sodbury On-the-Hill message boards!</h3>    <div>     Your email address is <a href="mailto:${user.emailAddress}">${user.emailAddress}</a>.  </div>  </body>    </html>

程式碼

package com.foo;    import org.apache.velocity.app.VelocityEngine;  import org.springframework.mail.javamail.JavaMailSender;  import org.springframework.mail.javamail.MimeMessageHelper;  import org.springframework.mail.javamail.MimeMessagePreparator;  import org.springframework.ui.velocity.VelocityEngineUtils;    import javax.mail.internet.MimeMessage;  import java.util.HashMap;  import java.util.Map;    public class SimpleRegistrationService implements RegistrationService {       private JavaMailSender mailSender;     private VelocityEngine velocityEngine;       public void setMailSender(JavaMailSender mailSender) {        this.mailSender = mailSender;     }       public void setVelocityEngine(VelocityEngine velocityEngine) {        this.velocityEngine = velocityEngine;     }       public void register(User user) {          // Do the registration logic...          sendConfirmationEmail(user);     }       private void sendConfirmationEmail(final User user) {        MimeMessagePreparator preparator = new MimeMessagePreparator() {           public void prepare(MimeMessage mimeMessage) throws Exception {              MimeMessageHelper message = new MimeMessageHelper(mimeMessage);              message.setTo(user.getEmailAddress());              message.setFrom("[email protected]"); // could be parameterized...              Map model = new HashMap();              model.put("user", user);              String text = VelocityEngineUtils.mergeTemplateIntoString(                 velocityEngine, "com/dns/registration-confirmation.vm", model);              message.setText(text, true);           }        };        this.mailSender.send(preparator);     }  }
<?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">       <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">        <property name="host" value="mail.csonth.gov.uk"/>     </bean>       <bean id="registrationService" class="com.foo.SimpleRegistrationService">        <property name="mailSender" ref="mailSender"/>        <property name="velocityEngine" ref="velocityEngine"/>     </bean>       <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">        <property name="velocityProperties">           <value>              resource.loader=class              class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader           </value>        </property>     </bean>    </beans>

Tags: