Nowadays, it’s very popular to have applications, that can somehow notificate people.We’re gonna use emails to send text and html mails to someone.Whar requirements do we need?
Possibility to send simple text emails Posibility to send html emails. Of course, to send emails, we need to have some template engine. We will use handlebars for that.
We will use
Spring. Maven as build tool Java Mail package Handlebars template engine Greenmail for “mocking” email server.
We need to have four subpackages, exception package for having custom exceptions, model package for storing our model, sender package for main functionality and template package for storing template service.
Your pom.xml should have similar structure
So, let’s create
We created all required models and resources for further developing, so let’s start adding core functionality
Have ever you ever think about sending emails with html content ? Imagine, your application sends email with some pretty organized html page. Sound great.
To do such things, of course, you need to have template engine.
I prefer Handlebards template engine.
if you have template in your resources/templates folder with name template1.html, then you should call handlebars.compile(“template1”); in your code.
It’s up to you how you will use this functionality, you can think about that on your spare time, I propose to use some sort of little services for each case, for example: sometimes you definitely know, that you will have constant amount of recipients, that will receive email, sometimes you know what will be the topic of your email, so , for each of that cases you can write separate service.
Something like that.
Your resources folder should like that
Greenmail is a fake server, that will allow you to register your beans in Spring. Also, you can use greenforest in your tests, receive mails, etc.
How to connect it with your spring application
To connect this example with your application, you need to include mail-context.xml in your Spring context.
I use something like this for importing my module.
If you will have some questions - feel free to ask me.