ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Using Groovy to Send Emails
Pages: 1, 2, 3

Taming JavaMail

Java has its own answer to interaction with email-related systems: JavaMail. JavaMail is an optional extension for the standard edition of Java and is included in the enterprise edition. It proves to be a useful choice if you are already working in an Enterprise container or if you need the full power of handling MIME types.

Here is what our code would look like:

import javax.mail.*
import javax.mail.internet.*

port = 1025
fixture = new EmailFixture(port)

props = new Properties()
props.put('mail.smtp.host', 'localhost')
props.put('mail.smtp.port', port.toString())
session = Session.getDefaultInstance(props, null)

// Construct the message
msg = new MimeMessage(session)
devteam = new InternetAddress('devteam@mycompany.org')
partners = new InternetAddress('partners@mycompany.org')
msg.from = new InternetAddress('cruise@mycompany.org')
msg.sentDate = new Date()
msg.subject = 'Successful build'
msg.setRecipient(Message.RecipientType.TO, devteam)
msg.setRecipient(Message.RecipientType.CC, partners)
msg.setHeader('Organization', 'mycompany.org')
msg.setContent('Successful build for ' + new Date(),

// Send the message

                           subject:'Successful build')

Some points of interest:

  • Groovy automatically converts checked exceptions into runtime exceptions for you, so there is no need to have a try ... catch block around statements such as Transport.send(msg), though you can if you want.

Leveraging the Spring Framework

Spring is a full-stack Java/JEE application framework. It has many features that make Java development more productive, and also has great Groovy integration. The part of Spring we are most interested in is its email services, but we are also going to make use of its bean wiring capabilities.

Spring makes it easy to create and use functionality encapsulated in independent and easily testable beans. Let's create such a bean that encapsulates our email-sending functionality and call the bean BuildNotifier. It in turn will make use of Spring's underlying email capabilities.

package org.mycompany

import org.springframework.mail.*

class BuildNotifier {
    def MailSender mailSender
    def SimpleMailMessage templateMessage
    def sendEmail(internalBuild) {
        def msg = new SimpleMailMessage(templateMessage)
        msg.text = 'Successful build for ' + new Date()
        msg.from = 'cruise@mycompany.org'
        if (!internalBuild)
            msg.cc = ['partners@mycompany.org'] as String[]

The mailSender and templateMessage beans are initialized for us by Spring. We'll see how later in the XML wiring file. Typically, any properties that don't change can actually be set in the wiring file (the to address is set in the wiring file as an example). Information that may change—e.g., the cc field, which is optionally set, and the text, which includes the current date and time—need to be set within the bean itself.

With our build notifier helper bean ready to go, we can now write our mail application again. It turns out to be fairly simple.

import org.springframework.context.support.*

ctx = new ClassPathXmlApplicationContext('beans.xml')
fixture = ctx.getBean('emailFixture')
notifier = ctx.getBean('buildNotifier')

                           subject:'Successful build')

The final piece that is missing in our Spring example is the wiring file. This tells the Spring framework how our beans are configured together and sets any static properties. Here is what it would look like:

<beans xmlns="http://www.springframework.org/schema/beans"
    <bean id="emailFixture" class="EmailFixture">
        <constructor-arg type="int" value="1025"/>
    <bean id="mailSender"
        <property name="host" value="localhost"/>
        <property name="port" value="1025"/>
    <bean id="templateMessage"
        <property name="to" value="devteam@mycompany.org"/>
        <property name="subject" value="Successful build"/>
    <bean id="buildNotifier" class="org.mycompany.BuildNotifier">
        <property name="mailSender" ref="mailSender"/>
        <property name="templateMessage" ref="templateMessage"/>

Note that properties such as port, host, the to address, and the subject are all constant fields and are defined here in one file for easy reconfiguration. See the Spring documentation for further details about how we could even supply the build notifier bean as an embedded Groovy script in the wiring file itself.

Pages: 1, 2, 3

Next Pagearrow