Email Service in Kotlin with Apache FreeMarker

Archana
4 min readJun 10, 2021

Are you searching for the simplest way of how you can develop an email service that can send and schedule sending of the emails with template of your choice? Then you might find some useful insights in this article, So let’s get started…

Photo by Daria Nepriakhina on Unsplash

Building Email body with Apache FreeMarker template

Apache FreeMarker is a template engine that allows using of data models or objects within HTML template by making use of interpolation and those object values would be substituted at run time.

data model + template => Output (Typically html)

So let’s say we have a data model MailRequest.kt with following properties.

So below is the example of a template where you have used data model properties as placeholders. For example ${mailRequest.name}, which would be replaced at runtime.

In the above template, we have just scratch the surface. There are many more complex use cases that are covered in the official manual, which are worth going through.

Adding template configurations

Once you have a template, you need to configure how you want to load your template as there are multiple ways of doing it. you can refer to various options in official documentation. Here we will be loading template from a public URL as in my case I would host the template in a public google cloud bucket for simplicity. You can pass this URL via environment variable as you would get an advantage of switching between multiple design templates that operate on same object!!!

Writing a email service in Kotlin

We will be making use of javax.mail library in order to send the mails over the internet.

Before starting with the implementation let’s just take a glance of what the basic flow of an email over the internet looks like. So basically you send out an email using your mail client, if you are connected to the internet using SMTP protocol your mail server(Google in this case could be any custom domain any-username@customDomain.com) will be able to fetch the email and based on the recipient email address-domain it checks the DNS server and if the domain is valid then locates the Recipient mail server and transfers the mail you sent to the Recipient mail server via SMTP protocol and then using IMAP/POP protocol the mail would be downloaded to recipient’s mail client

Now you have a basic idea of where exactly the SMTP protocol lies, let’s start with the implementation.

Lets first check how you can send emails with your private mail address with mail servers like google/yahoo/rediff etc..

Using Custom domain and Email for sending Emails

Since we have made the from/to email, subject and other dynamic variables to be taken from the environment variables we are free to use any email Id and the SMTP host address would be provided by the entity from whom you purchased the email associated to your domain.The advantage that you will get out of custom email with your domain is the limit on mails/day would be many times more than what GMAIL’s per day limit is on sending emails and of-course your users would have more trust if the mail is from some custom domain which they have visited, Also less chances of getting into Spam folder.

you can simply replace all the configurable parameters, basically

  1. Email/password
  2. SMTP host

Invoking the mail Service asynchronously with coroutineScope

The mail sending could be a part of some other operation that you are trying to perform, For example User registration, you don’t want the user to wait till the mail is sent and then respond, it could be done in the background too. So the efficient way that Koltin as a language offers is making use of coroutines. Lets see how this could be achieved.

This IO scope offloads the task of sending mail to other shared pool of threads which is basically dependent on the underlying system configuration.

CoroutineScope(IO).launch

Automate Email sending with scheduler

You can also have a use case where you need to schedule mails after every “X” units of time, a typical use case could be sending reminder emails to your users, In such cases you can simply extend the Timer provided by Kotlin which is basically a wrapper around Timer in java.

Alternate Options

There are few other options available if you don’t want to get into drafting your template or into the details of SMTP host and other configurable options that Javax.mail provides, you can check these alternatives, They provide multiple API’s for different services like sending mails/mail stats/maintaining user subscription groups and much more. Each of these provide a certain free tier but you can opt out for appropriate plans if your needs don’t fit the free plans

  1. MailGun
  2. MailJet
  3. SendGrid
  4. AmazonSES

In general what you need to do is to create an account with any of them and then register the sender email Id through which you would be sending emails to your users and you will be given an API key which you can use for accessing any of the API’s. This API key would basically authorize you to be the actual sender. Moreover they also provide a platform or UI/API to create your template either with drag and drop of UI elements or with the code. Choose as per your needs and start building your email service!!

Hope this article gave you some insight & Happy learning!

--

--