Skip to main content

Kotlin + Spring + Vue: Email

Final most common feature for web application is the email sending.
Let's do it!

I recommend to use any public email server for this feature. This tutorial is based on using Google Mail.

Also we will use Thymeleaf framework to create email templates in this tutorial.

Thymeleaf is a Java XML/XHTML/HTML5 template engine that can work both in web (servlet-based) and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer of MVC-based web applications, but it can process any XML file even in offline environments. It provides full Spring Framework integration.
Wikipedia

Objectives

  • Send simple text email message
  • Send message with HTML content
  • Send message with HTML content using template 

Backend

pom.xml

Add the following dependencies to pom.xml:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.4</version>
</dependency>



application.properties

Add to application.properties:

# SMTP
spring.mail.host=${SMTP_MAIL_HOST}
spring.mail.port=${SMTP_MAIL_PORT}
spring.mail.username=${SMTP_MAIL_USERNAME}
spring.mail.password=${SMTP_MAIL_PASSWORD}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.enable = true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000



Environment Variables

Add the following environment variables (or add startup parameters) using your email server configuration and credentials:

  • SMTP_MAIL_HOST
  • SMTP_MAIL_PORT
  • SMTP_MAIL_USERNAME
  • SMTP_MAIL_PASSWORD

Google Email Server Configuration

Email Service

Create package email and add interface EmailService there, where we define the methods for email sending:

Then add bean EmailServiceImpl:
  • We use auto-configured Spring's Email Sender to send the messages
  • Send simple text message is quite easy - add text to body and send
  • HTML messages we define as Mime Type messages and content as "text/html"
  • We use Spring Template Engine to process Thymeleaf HTML template
  • We have to point the of the attachment if we want to send an email with attachment. That's why it's much more easy to use public server-hosted images, documents, etc.

Thymeleaf Template

Create file emailTemplate.html in src/main/resources/templates/:

BackendController

Update BackendController by adding methods for sending the email messages:

import com.kotlinspringvue.backend.email.EmailServiceImpl
import com.kotlinspringvue.backend.web.response.ResponseMessage
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.ResponseEntity
import org.springframework.http.HttpStatus



@Autowired
lateinit var emailService: EmailServiceImpl

@Value("\${spring.mail.username}")
lateinit var addressee: String



@GetMapping("/sendSimpleEmail")
@PreAuthorize("hasRole('USER')")
fun sendSimpleEmail(): ResponseEntity<*> {
     try {
          emailService.sendSimpleMessage(addressee, "Simple Email", "Hello! This is simple email")
     } catch (e: Exception) {
          return ResponseEntity(ResponseMessage("Error while sending message"),
          HttpStatus.BAD_REQUEST)
     }
     return ResponseEntity(ResponseMessage("Email has been sent"), HttpStatus.OK)
}

@GetMapping("/sendTemplateEmail")
@PreAuthorize("hasRole('USER')")
fun sendTemplateEmail(): ResponseEntity<*> {
     try {
          var params:MutableMap<String, Any> = mutableMapOf()
          params["addresseeName"] = addressee
          params["signatureImage"] = "https://coderlook.com/wp-content/uploads/2019/07/spring-by-pivotal.png"
          emailService.sendSimpleMessageUsingTemplate(addressee, "Template Email", "emailTemplate", params)
     } catch (e: Exception) {
          return ResponseEntity(ResponseMessage("Error while sending message"),
          HttpStatus.BAD_REQUEST)
     }
     return ResponseEntity(ResponseMessage("Email has been sent"), HttpStatus.OK)
}

@GetMapping("/sendHtmlEmail")
@PreAuthorize("hasRole('USER')")
fun sendHtmlEmail(): ResponseEntity<*> {
     try {
          emailService.sendHtmlMessage(addressee, "HTML Email", "<h1>Hello!</h1><p>This is HTML email</p>")
     } catch (e: Exception) {
          return ResponseEntity(ResponseMessage("Error while sending message"),
          HttpStatus.BAD_REQUEST)
     }
     return ResponseEntity(ResponseMessage("Email has been sent"), HttpStatus.OK)
}

  • Notice how parameters are passed to the message template - using MutableMap<String, Any>.And now backend is completed and we have to create the interface for email sending
  • We are sending messages to ourselves (recipient=sender) to ensure that feature works

Frontend

Let's create a new component Email.vue where we will place buttons for sending every type of messages:

IMPORTANT: Don't forget to include the router to router.js and add a tab to navigation bar (App.vue).



The simple text message:

Message contains HTML code:

Message based on HTML template:


Ways to Improve

  • Implement sending email with an attachment 
  • Send email with an attachment hosted at your application server

Links


Comments

Popular posts from this blog

Make Authentication More Secure With Cookies Email Registration Confirmation That's all for this year. See you in 2020!

Kotlin + Spring Boot + Vue.js: + Gradle

Hello, dear visitors! I added two new articles to the Fullstack section: Kotlin + Spring + Vue: Migration from Maven to Gradle Kotlin + Spring + Vue: Deploy to Heroku with Gradle I'll be glad if you will find then useful for yourself.

Kotlin + Spring Boot + Vue.js

Hello there! I've published my first set of articles about developing web applications using Kotlin , Spring Boot and Vue.js : Koltin + Spring Boot + Vue.js Here are the contents of this set: Introduction Start CI/CD REST API Database Connection Authentication Spam Protection (reCAPTCHA) Email