前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring-email官方翻译

spring-email官方翻译

作者头像
逝兮诚
发布2019-10-30 20:02:59
7520
发布2019-10-30 20:02:59
举报
文章被收录于专栏:代码人生代码人生

官方地址: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 还提供一个回调接口来准备MimeMessageorg.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="customerservice@mycompany.com"/>
  <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("mail@mycompany.com"));
                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("test@host.com");
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("test@host.com");

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("test@host.com");

// 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("webmaster@csonth.gov.uk"); // 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>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-06-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Email
    • Introduction
      • Usage
        • Basic MailSender and SimpleMailMessage usage
        • Using the JavaMailSender and the MimeMessagePreparator
    • Using the JavaMail MimeMessageHelper
      • Sending attachments and inline resources
        • Attachments
        • Inline resources
      • Creating email content using a templating library
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档