Send Emails using Angular + Spring Boot + Thymeleaf

Chinthaka Jayatilake
LinkIT
Published in
4 min readOct 8, 2019
Photo by Krsto Jevtic on Unsplash

Thymeleaf is a modern server-side Java template engine for both web and standalone environments. The main goal of it is to bring elegant natural templates to the development workflow. HTML templates are written in Thymeleaf look and work like HTML.

Here we will be having an Angular front-end from which we will be collecting data using a simple form and along with it a Spring Boot back-end to send the Email.

Lets first start with the Angular project. Use the below command to create a new project.

ng new project_name

Now we need to create the HTML form to collect data. So let us move to the app.component.html file.

<h1>Enter the following details</h1><table>  <tr>
<td><span>Name</span></td>
<td><input type="text" [(ngModel)]="dataset.name" name="name"></td>
</tr>
<tr>
<td><span>Age(Integer)</span></td>
<td><input type="number" [(ngModel)]="dataset.age" name="age"></td></tr>
<tr>
<td><span>Country</span></td>
<td><input type="text" [(ngModel)]="dataset.country" name="country"></td>
</tr>
<tr>
<td><span>Send Email to</span></td>
<td><input type="text" [(ngModel)]="dataset.email" name="email"
</td>
</tr>
<tr>
<td></td>
<td><button (click)="onSubmit()">Submit</button></td>
</tr>
</table>

Next, we need to move to the app.component.ts file. Here we will be using the HttpClient to communicate with the Spring Boot back-end.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { title = 'EmailTemplate'; dataset: Details = {
name:'',
age:null,
country:'',
email:''
};
constructor(private https: HttpClient){ } onSubmit(){ this.https.post<Details>('http://localhost:8080/testapp/getdetails', this.dataset).subscribe( res => {
this.dataset = res;
console.log(this.dataset);
alert('Email Sent successfully');
this.dataset.age = null;
this.dataset.name = '';
this.dataset.country = '';
this.dataset.email = '';
});
}
}
interface Details{ name:string;
age:number;
country:string;
email:string;
}

It is important to make sure that all the imports which are mentioned at the beginning of the component.ts files are present in the project node modules folder. If not they must be installed as below.

npm install imported_file_name

Now it is time to move to the Spring Boot project. You can create a Spring Boot project easily by using the below link.

To start with we need to add the below dependencies to our pom.xml file as we need to import them to our project to work with them.

<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>

<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>2.1.2</version>
</dependency>

</dependencies>

As we will be needing to send the emails through an email account, we need to enter the credentials, host, and port details to the application properties file. Here we will be using the SMTP protocol to send emails. So we need to configure that as well.

spring.mail.host=smtp.gmail.com
spring.mail.port=587
#(above can be used for gmail)
spring.mail.username=_email_address_
spring.mail.password=_password_
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

Next is creating a class to get the variables in the front-end.

public class Details {

private String name;

private int age;

private String country;

private String email;

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}
}

Now we need to configure the SpringTemplateEngine and the SpringResourceTemplateResolver as we will be needing them once we are working with Thymeleaf templates.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;

import java.nio.charset.StandardCharsets;

@Configuration
public class EmailThymeleafConfiguration {


@Bean
public SpringTemplateEngine springTemplateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver());
return templateEngine;
}

@Bean
public SpringResourceTemplateResolver htmlTemplateResolver() {
SpringResourceTemplateResolver pdfTemplateResolver = new SpringResourceTemplateResolver();
pdfTemplateResolver.setPrefix("classpath:/templates/");
pdfTemplateResolver.setSuffix(".html");
pdfTemplateResolver.setTemplateMode(StandardTemplateModeHandlers.HTML5.getTemplateModeName());
pdfTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return pdfTemplateResolver;
}
}

Now we can write our main few methods in the controller class to get the data from the front-end and to initialize the templates while passing the variables as parameters to them.

import com.blog.example.EmailTemplate.dto.Details;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine;
import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/testapp")
@Controller
public class EmailSender {

@Autowired
SpringTemplateEngine templateEngine;

@Autowired
private JavaMailSender sender;

@RequestMapping("/getdetails")
public @ResponseBody Details sendMail(@RequestBody Details details) throws Exception {

MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());

Map<String, Object> model = new HashMap<String, Object>();
model.put("name",details.getName());
model.put("age",details.getAge());
model.put("country",details.getCountry());

Context context = new Context();
context.setVariables(model);
String html = templateEngine.process("email-template", context);

try {
helper.setTo(details.getEmail());
helper.setText(html,true);
helper.setSubject("Test Mail");
} catch (javax.mail.MessagingException e) {
e.printStackTrace();
}
sender.send(message);

return details;

}
}

We also need to create an HTML file to define how our email would appear once the receiver receives it. This will be used as the email template.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Template</title>
</head>
<body>

<h1>This is just a sample html page</h1>

<h2>Below are the details that were passed to the html page</h2>

<p th:text="${'Name : ' + name}"></p>
<p th:text="${'Age :' + age}"></p>
<p th:text="${'Country : ' + country}"></p>

<p><b>You can create the page the way you wish to have your Email body using HTML tags</b></p>

<p><b>Bootstrap can be added to design. Images can be added. All according to your preference</b></p>

</body>
</html>

That’s it. We have completed the implementation and it is time to test…

Simple… Isn’t it? I hope it was clear to you. The project source code can be viewed and downloaded from GitHub. You are free to use it in your projects.

Cheers!! Have a pleasant day!!

Visit my Official Blog Site to send in your queries directly to me and to read more articles by me….

--

--