Core Java

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
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button