`
grantbb
  • 浏览: 272372 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

用Spring邮件抽象层发送邮件

    博客分类:
  • JAVA
阅读更多
18.1. Introduction
介绍
Spring provides a higher level of abstraction for sending electronic mail which shields the user from the specifics of underlying mailing system and is responsible for a low level resource handling on behalf of the client.

Spring 支持一个更高层的抽象用来发送电子邮件,它隐藏底层邮件系统的细节并且代表客户端对低级别的控制 。

18.2. Spring mail abstraction structure
Spring邮件抽象结构
The main package of Spring mail abstraction layer is org.springframework.mail package. It contains central interface for sending emails called MailSender and the value object which encapsulates properties of a simple mail such as from, to, cc, subject, text called SimpleMailMessage. 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 JavaDocs for more information on mail exception hierarchy.

Sring邮件抽象层的主要包是:org.springframework.mail 包。它包含叫MailSender为发送邮件的核心接口和包含简单邮件属性例如from,to,cc,subject,text叫 SimpleMailMessage的值对象. 这个包也包含一个检查异常的层次,它支持一个更高级别的抽象超过低级别的邮件系统异常伴随根异常存在MailException. 请参考JavaDocs为更多的信息杂邮件异常层次。

Spring also provides a sub-interface of MailSender for specialized JavaMail features such as MIME messages, namely org.springframework.mail.javamail.JavaMailSender It also provides a callback interface for preparation of JavaMail MIME messages, namely org.springframework.mail.javamail.MimeMessagePreparator

Spring也支持一个MailSender的专用于JavaMail特征例如MIME消息子接口,命名为 org.springframework.javamail.JavaMailerSener。它也支持一个为JavaMail MIME信息的准备回调接口,命名为 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
     * 发送给定的简单邮件信息
     * @参数 simpleMessage  发送的信息
     * @throws MailException 假设信息,证明或发送错误
     */
   
    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[])
     * 创建一个新的JavaMail MimeMessage 为潜在的JavaMail的发送者的会话.
     * 需要被调用来创建MimeMessage实例,它可以被客户准备并且被传递发送(MimeMessage).
     * @return 这个新的MimeMessage 实例
     * @see #send(Message)
     * @sess #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;

}

18.3. Using Spring mail abstraction
使用Spring邮件抽象
Let’s assume there is a business interface called OrderManager
让我们假定这里有一个商业接口叫OrderManager

public interface OrderManager {

    void placeOrder(Order order);
  
}

and there is a use case that says that an email message with order number would need to be generated and sent to a customer placing that order. So for this purpose we want to use MailSender and SimpleMailMessage
并且这里有一个有用案例,可以说一个伴随订单编号的邮件信息将需要被产生并且发送给一个客户处理这个订单。所以为这个目的我们想要使用MailSender和SimpleMailSender.


Please note that as usual, we work with interfaces in the business code and let Spring IoC container take care of wiring of all the collaborators for us.

请注意照常,我们工作使用在商业代码中的接口并且让Spring Ioc 容器关心为我们的所有合作者。

Here is the implementation of OrderManager
这里是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 business calculations....
        //... * Call the collaborators to persist the order

        //Create a thread safe "sandbox" of the message
        SimpleMailMessage 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 on
            System.err.println(ex.getMessage());          
        }
    }
}
Here is what the bean definitions for the code above would look like:
这里是这个为这个以上代码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>
Here is the implementation of OrderManager using MimeMessagePreparator callback interface. Please note that the mailSender property is of type JavaMailSender in this case in order to be able to use 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 business calculations....
        //... * Call the collaborators to persist the order
      
      
        MimeMessagePreparator 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 on
            System.err.println(ex.getMessage());          
        }
    }
}
If you want to use JavaMail MimeMessage to the full power, the MimeMessagePreparator is available at your fingertips.
如果你想使用JavaMail  MimeMessage来使得足够强大,MimeMessagePreparator 是可以利用的。

Please note that the mail code is a crosscutting(横切的) concern(关注)  and is a perfect candidate(候选) for refactoring into a custom Spring AOP advice, which then could easily be applied to OrderManager target. Please see the AOP chapter.


18.3.1. Pluggable MailSender implementations
Spring comes with two MailSender implementations out of the box - the JavaMail implementation and the implementation on top of Jason Hunter’s MailMessage class that’s included in http://servlets.com/cos (com.oreilly.servlet). Please refer to JavaDocs for more information.

18.4. Using the JavaMail MimeMessageHelper
One of the components that comes in pretty handy when dealing with JavaMail messages is the org.springframework.mail.javamail.MimeMessageHelper. It prevents you from having to use the nasty APIs the the javax.mail.internet classes. A couple of possible scenarios:

18.4.1. Creating a simple MimeMessage and sending it
Using the MimeMessageHelper it’s pretty easy to setup and send a MimeMessage:

// of course you would setup the mail sender using
// DI in any real-world cases
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("mail.host.com");

MimeMessage message = sender.createMimeMesage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo("test@host.com");
helper.setText("Thank you for ordering!");

sender.send(message);

18.4.2. Sending attachments and inline resources
Email allow for attachments, but also for inline resources in multipart messages. Inline resources could for example be images or stylesheet you want to use in your message, but don’t want displayed as attachment. The following shows you how to use the MimeMessageHelper to send an email along with an inline image.

JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("mail.host.com");

MimeMessage message = sender.createMimeMesage();

// 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);

// if you would need to include the file as an attachment, use
// addAttachment() methods on the MimeMessageHelper

sender.send(message);
  
Inline resources are added to the mime message using the Content-ID specified as you’ve seen just now (identifier1234 in this case). The order in which you’re adding the text and the resource are VERY important. First add the text and after that the resources. If you’re doing it the other way around, it won’t work!
分享到:
评论
1 楼 tryyong 2008-08-14  
   

相关推荐

    spring邮件抽象层详解

    Spring邮件抽象层是Spring框架提供的一套用于发送电子邮件的高级接口,它隐藏了与底层邮件系统交互的复杂性,使得开发者能够以一种简洁的方式发送邮件。这个抽象层主要包含在`org.springframework.mail`包中,提供了...

    spring各种邮件发送

    Spring邮件抽象层的主要包为org.springframework.mail。它包括了发送电子邮件的主要接口MailSender,和值对象SimpleMailMessage,它封装了简单邮件的属性如from, to,cc, subject,text。 包里还包含一棵以...

    Spring进阶—如何用Java代码实现邮件发送

    此外,Spring的邮件抽象层还有一套异常处理机制,以更好地封装和处理邮件系统可能出现的异常。 使用Spring发送邮件的基本步骤如下: 1. 添加Spring核心库和相关的邮件发送库(如JavaMail API)到项目依赖中。 2. ...

    spring集成邮件服务

    同时,如果你需要发送的邮件具有模板,可以考虑使用Spring的`Thymeleaf`或者其他模板引擎来动态生成邮件内容。 总的来说,Spring集成邮件服务使得在Java应用中发送邮件变得简单且灵活。通过合理的配置和编程,你...

    ActiveMQ与Spring整合之异步发送邮件

    2. **Spring JMS抽象层**:Spring通过`JmsTemplate`类提供了简化JMS操作的抽象层,简化了消息的发送和接收。 3. **容器管理的bean**:Spring允许在bean中注入`ConnectionFactory`和`Destination`,使得配置更简洁。...

    spring整合quartz定时发送邮件

    Spring 整合 Quartz 定时发送邮件是一种常见的任务调度场景,用于定期执行如发送通知、报告等操作。Quartz 是一个开源的作业调度框架,它允许开发者创建、调度和管理任务。而Spring作为一个强大的企业级应用开发框架...

    spring整合freemarker发送邮件例子

    在这个场景中,Spring 提供了电子邮件服务的抽象层,使得发送邮件变得简单。 2. **FreeMarker**:FreeMarker 是一个基于模板的 Java 模板引擎,常用于生成动态 HTML、XML 或其他文本格式的文档。在这里,我们使用 ...

    SpringMailTest.zip

    Spring邮件抽象层的主要包为org.springframework.mail。它包括了发送电子邮件的主要接口MailSender(实现类为org.springframework.mail.javamail.JavaMailSenderImpl,下面会用到改实现类)和封装了简单邮件属性的值...

    Java基于JDK1.6基础上Spring2.5.6版本上发送邮件功能需要的依赖lib.zip

    2. **Spring邮件支持**: - Spring 2.5.6提供了`JavaMailSender`接口,该接口定义了发送邮件的基本方法,如`send(SimpleMailMessage message)`和`send(MailMessage[] messages)`。 - `SimpleMailMessage`是一个预...

    SpringUseJavaMailSendEmail(spring使用javamail发送邮件的例子)

    首先,我们需要理解Spring框架中的邮件服务抽象。Spring提供了一个`JavaMailSender`接口,该接口定义了发送邮件的基本方法。我们可以通过配置Spring的bean来实现这个接口,以便与JavaMail API集成。在`...

    Spring+Freemarker 使用163发HTML格式的邮件

    标题 "Spring+Freemarker 使用163发HTML格式的邮件" 涉及到的主要知识点是使用Spring框架集成Freemarker模板引擎来发送HTML格式的邮件,通过163邮箱服务实现。以下是对这些技术的详细介绍: 1. **Spring框架**: ...

    spring发送邮件

    这两种方法都基于JavaMail API,但Spring提供了一层抽象,使得邮件发送的代码更加简洁和易于管理。 1. **JavaMailSender接口**: JavaMailSender接口提供了发送简单文本邮件、HTML邮件以及带有附件的邮件的方法。...

    Spring mail 使用多个账号发送带有附件的HTML邮件

    Spring Mail则是在这个API之上提供了一层抽象,使得邮件发送的代码更加简洁和易于管理。 1. **配置Spring Mail**: 在Spring应用中配置Spring Mail通常涉及以下步骤: - 添加依赖:确保项目中包含了`spring-...

    Spring Boot 发送邮件功能案例分析

    Spring 框架使用 JavaMailSender 接口为发送邮件提供了一个简单的抽象,并且 Spring Boot 也为它提供了自动配置和一个 starter 模块。如果 spring.mail.host 和相关的库(通过 spring-boot-starter-mail 定义)都...

    Java网络编程-基于Spring的邮件编程-1

    Spring框架为此提供了更简洁的抽象,使得邮件发送变得简单易行。 Spring中的`JavaMailSender`接口是发送邮件的核心接口,它定义了发送简单邮件、带附件的邮件等方法。我们可以通过Spring的配置文件或者Java配置来...

    java邮件发送组件

    在实际开发中,除了直接使用Java Mail API,还可以选择一些成熟的Java邮件发送库,例如Apache Commons Email、Spring Framework的MailSender接口等,它们提供了更友好的API和额外的特性,可以帮助开发者快速实现邮件...

    Spring发送Email

    JavaMail API是Java中用于处理邮件的规范,而Spring Mail则提供了一层抽象,简化了邮件发送的配置和实现。 要使用Spring Mail,我们首先需要在项目中引入相应的依赖。如果你的项目是Maven项目,可以在pom.xml文件中...

Global site tag (gtag.js) - Google Analytics