JasperReports is a library entirely written in Java and it is able to use data coming from
any kind of data source and produce pixel-perfect documents that can be viewed, printed or exported in a variety of
document formats including HTML, PDF, Excel, OpenOffice and Word.
Introduction
We will look at two types of HTML emails that can be sent with Spring’s abstraction of JavaMail:
HTML email with no inline
HTML email with inline (using image resources)
Generally when sending emails as HTML with Spring, you can use Thymeleaf, Freemaker etc to template your HTML.
In this post we will look at how to achieve the same thing using JasperReports.
What we will not be doing in this post is how to send attachments with Spring’s abstraction of JavaMail.
To complete this guide, download (zip|
tar.gz)
and unzip the source repository for this guide. You also need to set the following environment variables:
MAIL_HOST
MAIL_PASSWORD
MAIL_PORT
MAIL_USERNAME
HTML Mail without Inline
Download and extract the base project if you haven’t already done so. Create the class HtmlEmailService that
implements the EmailService. We will implement sendHtmlEmail() for the time being:
The @Async annotation tells the Spring
Framework to run the methods of EmailService asynchrousnously when invoked.
The html of sendHtmlEmail() parameter contains the HTML markup.
The html String parameter is specified by
(src/main/resources/reports/html.jrxml). Before you execute, do not forget
to set the values of com.juliuskrah.cron and com.juliuskrah.mail.recipients[0].email in the configuration file.
Be sure to set an appropriate cronexpression.
Jasper HTML Email
Not very elegant, but you get the general idea.
HTML Mail with Inline
Generating HTML in JasperReports with image resources is a bit tricky. JasperReports handles the image resources
separately before associating them to the HTML.
We will implement the generateInlineHtmlReport() to handle the image resources.
The implementation of generateInlineHtmlReport() is similar to generateHtmlReport(). I will just highlight the
code change. You can view the full implementation in the linked file below:
Set an appropriate cron expression for com.juliuskrah.inline-cron and that’s all folks.
Conclusion
In this post we learned how to generate HTML mail with JasperReports with and without inline images.
As usual you can find the full example to this guide in the github repository. Until the next post, keep doing cool things .