Sending Email Using Spring Boot

Photo by Elena Mozhvilo on Unsplash
Photo by Elena Mozhvilo on Unsplash
This article will introduce how to use FreeMarker to create an email template, and use Spring Mail to send email through Gmail SMTP.

Back-end often needs to send email to users, such as registration completion, password forgotten, purchase completion, etc. This article will introduce how to use FreeMarker to create an email template, and use Spring Mail to send email through Gmail SMTP.

The complete code for this chapter can be found in .

FreeMarker

FreeMarker is a template engine that can be used to create templates for email content. First, we need to include the following dependency.

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-freemarker")
}

In application.properties, add the following configuration. spring.freemarker.template-loader-pathIs used to set the directory where the template file is. In the following example, we set it under src/resources/templates/.

spring.freemarker.cache=true
spring.freemarker.template-loader-path=classpath:/templates/

Add a new template file named EmailTemplate.ftlh under src/resources/templates/, and its content is as follows. In the content of the template file, there are two variables, ${logo}and ${content}. After that, we can programmatically replace the data we want in the places of the variables.

<html>
<body>

<div>
    <img src="cid:${logo}" />
</div>
<br/>
<div>${content}</div>

</body>
</html>

Spring Mail

Next, we will use Spring Mail to send email via STMP. First, we need to include the following dependency.

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-mail")
}

In application.properties, we use Gmail STMP as SMTP server.

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=<login username to smtp server>
spring.mail.password=<login password to smtp server>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.debug=true

All configurations are now complete. Next, we will use the following code to send email. In the code, we use JavaMailSender to send emails, but we do not include the dependency of JavaMailSender. This is because Spring Mail is based on JavaMailSender to implement sending email.

First, we call JavaMailSender.createMimeMessage() to create a MimeMessage. Then, use MimeMessageHelper to set the sender (from), receiver (to) and subject of the email.

Load the template file with FreeMarker, and call FreeMarkerTemplateUtils.processTemplateIntoString() to replace the logo and content into the template. Call MimeMessageHelper.setText() to pass the template content into the MimeMessage. Then, call MimeMessageHelper.addInline() to add the logo file to the MimeMessage. Note that addInline() must be called after setText(), otherwise the logo will not be displayed.

Finally, call JavaMailSender.send() to send the email.

@Service
class EmailService(private val javaMailSender: JavaMailSender, private val freemarkerConfig: Configuration) {
    fun sendEmail(to: String, subject: String, content: String) {
        val mimeMessage = javaMailSender.createMimeMessage()
        val helper = MimeMessageHelper(mimeMessage, true)
        helper.setFrom("Wayne's Talk <waynestalk@gmail.com>")
        helper.setTo(to)
        helper.setSubject(subject)

        val logoClassPathResource = ClassPathResource("static/logo.png")
        val logo = ByteArrayResource(logoClassPathResource.inputStream.readAllBytes())

        val parameters = mapOf(
            "logo" to "logo.png",
            "content" to content,
        )

        val template = freemarkerConfig.getTemplate("EmailTemplate.ftlh")
        val text = FreeMarkerTemplateUtils.processTemplateIntoString(template, parameters)
        helper.setText(text, true)

        // This line must be after helper.setText(), otherwise the logo won't be displayed
        helper.addInline("logo.png", logo, "image/png")

        javaMailSender.send(mimeMessage)
    }
}

Conclusion

Spring Mail is fairly simple to use. The main problem is how to generate complex email content. And this part can be easily achieved with FreeMarker. Used together, the two tools can easily generate complex email.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like