`
grantbb
  • 浏览: 268470 次
  • 性别: 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邮件抽象层详解,简单的方式发送email

    spring各种邮件发送

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

    SpringMailTest.zip

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

    Spring 2.0 开发参考手册

    6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. 其它资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点实施 7.2.3. AspectJ切入点表达式 7.2.4. ...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.1.1. @Configurable object的单元测试 6.8.1.2. 多application context情况下的处理 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来...

    spring chm文档

    Spring Framework 开发参考手册 Rod Johnson Juergen Hoeller Alef Arendsen Colin Sampaleanu Rob Harrop Thomas Risberg Darren Davison Dmitriy Kopylenko Mark Pollack ...19.2. 使用Spring JMS ...

    Spring中文帮助文档

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    开源框架 Spring Gossip

    简单邮件 HTML 邮件 内嵌图片或附档 排程 Spring则对 java.util.Timer提供了抽象封装,让您可以善用Spring的容器管理功能,而Spring对Quartz进行了封装,让它在使用上更加方便。 使用 ...

    Spring API

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    Spring.3.x企业应用开发实战(完整版).part2

    Spring3.0是Spring在积蓄了3年之久后,隆重推出的一个重大升级版本,进一步加强了Spring作为Java领域第一开源平台的翘楚地位。  Spring3.0引入了众多Java...附录A JavaMail发送邮件 附录B 在Spring中开发Web Service

    spring framework 开发参考手册

    你可以使用 IoC容器,在其上使用Struts,但是你也可以选择使用 Hibernate 整合代码或者 JDBC 抽象层。 我们将Spring设计为非侵入式的(并且以后也是如此),这意味着应用基本上不需要依赖框架本身 (或者肯定是最小...

    Spring Framework 开发参考手册

    你可以使用 IoC容器,在其上使用Struts,但是你也可以选择使用 Hibernate 整合代码或者 JDBC 抽象层。 我们将Spring设计为非侵入式的(并且以后也是如此),这意味着应用基本上不需要依赖框架本身 (或者肯定是最小...

    Spring in Action(第2版)中文版

    5.3.3使用spring对jdbc的dao支持类 5.4在spring里集成hibernate 5.4.1选择hibernate的版本 5.4.2使用hibernate模板 5.4.3建立基于hibernate的dao 5.4.4使用hibernate3上下文会话 5.5spring和java持久api ...

    Spring in Action(第二版 中文高清版).part2

    5.3.3 使用Spring对JDBC的DAO支持类 5.4 在Spring里集成Hibernate 5.4.1 选择Hibernate的版本 5.4.2 使用Hibernate模板 5.4.3 建立基于Hibernate的DAO 5.4.4 使用Hibernate 3上下文会话 5.5 Spring和Java...

    Spring in Action(第二版 中文高清版).part1

    5.3.3 使用Spring对JDBC的DAO支持类 5.4 在Spring里集成Hibernate 5.4.1 选择Hibernate的版本 5.4.2 使用Hibernate模板 5.4.3 建立基于Hibernate的DAO 5.4.4 使用Hibernate 3上下文会话 5.5 Spring和Java...

    Spring3.x企业应用开发实战(完整版) part1

    Spring3.0是Spring在积蓄了3年之久后,隆重推出的一个重大升级版本,进一步加强了Spring作为Java领域第一开源平台的翘楚地位。  Spring3.0引入了众多Java...附录A JavaMail发送邮件 附录B 在Spring中开发Web Service

    spring-email-master:使用spring4.3.4 发送邮件,三种方式:文本格式,HTML格式,velocity模版,Thymeleaf模版,使用模版以及策略设计模式实现同步和异步发送

    Spring Email抽象核心接口MailSender,其实现类JavaMailSenderImpl,在其中配置邮件 服务器host,pssword,协议等 。。。。。 1.发送简单的消息 SimpleMailMessage:发送简单的消息 2.发送丰富的消息(比如带有附件,内...

    Spring面试题

    没有使用一堆抽象工厂、服务定位器、单元素(singleton)和直接构造(straight construction),每一个对象都是用其协作对象构造的。因此是由容器管理协作对象(collaborator)。 Spring即使一个AOP框架,也是一IOC...

    128元尚硅谷Java视频教程_Spring Boot视频教程(下)整合篇

    着重介绍SpringBoot的与各大场景的整合使用,内容包括:缓存(整合Redis),消息中间件(整合RabbitMQ),检索(整合ElasticSearch),任务(异步任务,定时任务,邮件任务),安全(整合SpringSecurity),分布式...

    尚硅谷Java视频教程_Spring Boot视频教程(下)整合篇

    00、尚硅谷_SpringBoot_源码、课件 1、尚硅谷-SpringBoot高级-缓存-JSR107简介 2、尚硅谷-SpringBoot高级-缓存-Spring缓存抽象简介 3、尚硅谷-SpringBoot高级-缓存-基本环境搭建 4、尚硅谷-SpringBoot高级-缓存-@...

Global site tag (gtag.js) - Google Analytics