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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Embracing Reactive Programming With Spring WebFlux
  • Spring Boot Annotations: Behind the Scenes and the Self-Invocation Problem
  • Comparing ModelMapper and MapStruct in Java: The Power of Automatic Mappers
  • A Guide to Enhanced Debugging and Record-Keeping

Trending

  • Building AI Applications With Java and Gradle
  • Software Verification and Validation With Simple Examples
  • The Convergence of Testing and Observability
  • Build a Serverless App Fast With Zipper: Write TypeScript, Offload Everything Else
  1. DZone
  2. Coding
  3. Frameworks
  4. Tracking Exceptions - Part 4 - Spring's Mail Sender

Tracking Exceptions - Part 4 - Spring's Mail Sender

Roger Hughes user avatar by
Roger Hughes
·
Apr. 11, 14 · Interview
Like (1)
Save
Tweet
Share
12.08K 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

  • Embracing Reactive Programming With Spring WebFlux
  • Spring Boot Annotations: Behind the Scenes and the Self-Invocation Problem
  • Comparing ModelMapper and MapStruct in Java: The Power of Automatic Mappers
  • A Guide to Enhanced Debugging and Record-Keeping

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: