DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • AI-Based Threat Detection in Cloud Security
  • Memory Leak Due to Time-Taking finalize() Method
  • Docker Base Images Demystified: A Practical Guide
  • Docker Model Runner: Streamlining AI Deployment for Developers
  1. DZone
  2. Coding
  3. Frameworks
  4. Tracking Exceptions - Part 4 - Spring's Mail Sender

Tracking Exceptions - Part 4 - Spring's Mail Sender

By 
Roger Hughes user avatar
Roger Hughes
·
Apr. 11, 14 · Interview
Likes (1)
Comment
Save
Tweet
Share
12.9K Views

Join the DZone community and get the full member experience.

Join For Free

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…


The code for this blog is available on Github at: https://github.com/roghughe/captaindebug/tree/master/error-track.

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
Mail (Apple) Spring Framework

Published at DZone with permission of Roger Hughes, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: