Tracking Exceptions – Part 4 – Spring’s Mail Sender

If you’ve read any of the previous blogs in this series, you may remember that I’m developing a small but almost industrial strength application that searches log files for exceptions. You may also remember that I now have a class that can contain a whole bunch of results that will need sending to any one whose interested. This will be done by implementing my simple Publisher interface shown below.
 
 
 
 
 
 

public interface Publisher { 

  public <T> boolean publish(T report); 
}

If you remember, the requirement was:

7 . Publish the report using email or some other technique.

In this blog I’m dealing with the concrete part of the requirement: sending a report by email. As this is a Spring app, then the simplest way of sending an email is to use Spring’s email classes. Unlike those stalwarts of the Spring API, template classes such as JdbcTemplate and JmsTemplate, the Spring email classes are based around a couple of interfaces and their implementations. The interfaces are:

  1. MailSender
  2. JavaMailSender extends MailSender
  3. MailMessage

…and the implementations are:

  1. JavaMailSenderImpl implements JavaMailSender
  2. SimpleMailMessage implements MailMessage

Note that these are the ‘basic’ classes; you can send nicer looking, more sophisticated email content using classes such as: MimeMailMessage, MimeMailMessageHelper, ConfigurableMimeFileTypeMap and MimeMessagePreparator.

Before getting down to some code, there’s the little matter of project configuration. To use the Spring email classes, you need the following entry in your Maven POM file:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4</version>
</dependency>

This ensures that the underlying Java Mail classes are available to your application.

Once the Java Mail classes are configured in the build, the next thing to do is to set up the Spring XML config.

<!-- Spring mail configuration -->

     <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
          <property name="host" value="${mail.smtp.host}"/>
     </bean>

     <!-- this is a template message that we can pre-load with default state -->
     <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
          <property name="to" value="${mail.to}"></property>
            <property name="from" value="${mail.from}"/>
            <property name="subject" value="${mail.subject}"/>
     </bean>

For the purposes of this app, which is sending out automated reports, I’ve included two Spring beans: mailSender and mailMessage.mailSender, is a JavaMailSenderImpl instance configured to use a specific SMTP mail server, with all other properties, such as TCP port, left as defaults.

The second Spring bean is mailMessage, an instance of SimpleMailMessage. This time I’ve pre-configured three properties: ‘to’, ‘from’ and ‘subject’. This is because, being automated messages, these values are always identical.

You can of course configure these programatically, something you’d probably need to do if you were creating a mail GUI.

All this XML makes the implementation of the Publisher very simple.

@Service 
public class EmailPublisher implements Publisher { 

  private static final Logger logger = LoggerFactory.getLogger(EmailPublisher.class); 

  @Autowired 
  private MailSender mailSender; 

  @Autowired 
  private SimpleMailMessage mailMessage; 

  @Override 
  public <T> boolean publish(T report) { 

    logger.debug("Sending report by email..."); 
    boolean retVal = false; 
    try { 
      String message = (String) report; 
      mailMessage.setText(message); 
      mailSender.send(mailMessage); 
      retVal = true; 
    } catch (Exception e) { 
      logger.error("Can't send email... " + e.getMessage(), e); 
    } 

    return retVal; 
  } 

}

The Publisher class contains one method:publish, which takes a generic argument T report. This, as I’ve said before, has to be the same type as the argument returned by the Formatter implementation from my previous blog.

There are only really three steps in this code to consider: firstly, the generic T is cast to a String (this is where it’ll all fall over if the argument T report isn’t a String.

The second step is to attach the email’s text to the mailMessage and then to send the message using mailSender.send(…).

The final step is fulfil the Publisher contract by returning true, unless the email fails to send in which case the exception is logged and the return value is false.

In terms of developing the code that’s about it. The next step is to sort out the scheduling, so that the report is generated on time, but more on that later…

If you want to look at other blogs in this series take a look here…

  1. Tracking Application Exceptions With Spring
  2. Tracking Exceptions With Spring – Part 2 – Delegate Pattern
  3. Error Tracking Reports – Part 3 – Strategy and Package Private

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


4 + = twelve



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close