Email
Introduction Library dependencies The following additional jars to be on the classpath of your application in order to be able to use the Spring Framework's email library. The JavaMail mail.jar library The JAF activation.jar library All of these libraries are freely available on the web. 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 preparation of JavaMail MIME messages, called org.springframework.mail.javamail.MimeMessagePreparator
Usage Let's assume there is a business interface called OrderManager: 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 <interfacename>MailSender</interfacename> and <classname>SimpleMailMessage</classname> usage // Do the business calculations...// Call the collaborators to persist the order...// Create a thread safe "copy" of the template message and customize it// simply log it and go on... Find below the bean definitions for the above code: ]]><!-- this is a template message that we can pre-load with default state --> ]]>
Using the <interfacename>JavaMailSender</interfacename> and the <classname>MimeMessagePreparator</classname> 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: // Do the business calculations...// Call the collaborators to persist the order...// simply log it and go on... The mail code is a crosscutting concern and could well be a candidate for refactoring into a custom Spring AOP aspect, which then could be executed at appropriate joinpoints on the OrderManager target. The Spring Framework's mail support ships with the standard JavaMail implementation. Please refer to the relevant JavaDocs for more information.
Using the JavaMail <classname>MimeMessageHelper</classname> 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: // of course you would use DI in any real-world cases
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. // use the true flag to indicate you need a multipart message// let's attach the infamous windows Sample file (this time copied to c:/)
Inline resources The following example shows you how to use the MimeMessageHelper to send an email along with an inline image. // use the true flag to indicate you need a multipart message// use the true flag to indicate the text included is HTML", true); ]]>// let's include the infamous windows Sample file (this time copied to c:/) 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!
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 or Velocity 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 and Velocity becomes quite easy to do. Find below an example of using the Velocity template library to create email content.
A Velocity-based example To use Velocity to create your email template(s), you will need to have the Velocity libraries available on your classpath. You will also need to create one or more Velocity templates for the email content that your application needs. Find below the Velocity template that this example will be using. As you can see it is HTML-based, and since it is plain text it can be created using your favorite HTML or text editor. # in the com/foo/package

Hi ${user.userName}, welcome to the Chipping Sodbury On-the-Hill message boards!

Your email address is ${user.emailAddress}.
]]>
Find below some simple code and Spring XML configuration that makes use of the above Velocity template to create email content and send email(s). // Do the registration logic...// could be parameterized... resource.loader=class class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader ]]>