Sending HTML template base email using spring boot.
Hello Geeks, hope you all are doing well these days. Recently i was working in my project where a case came, where I had to send an email with attachment in specific format(basically template based).
So, after doing a quick research I came up with solution, In this particular blog post I am going to share the spring boot plugin i.e. free marker, to send template based multi lingual email.
So, first things first. Initiate a blank spring boot application with some of dependencies listed below:
1. web dependencies
2. jackson dependencies
3. lombok dependencies
4. mail dependencies
5. free marker dependencies
Here is the effective pom.xml, you can also use gradle instead of maven.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatechie</groupId>
<artifactId>spring-boot-email-freemarker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-email-freemarker</name>
<description>Trigger an email using spring boot freemarker</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<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-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.4.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Now, add some properties into your application.properties or application.yml file I am stick with application.properties file.
application.properties
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.gmail.com
spring.mail.username=your-gmail-id
spring.mail.password=your-gmail-password
spring.mail.port=587
spring.mail.protocol=smtp
spring.mail.test-connection=false
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.smtp.ssl.trust=smtp.gmail.com
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com
Now, create a configuration class
ApiConfig.java
package com.techreloded.email.api.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
@Configuration
public class ApiConfig {
@Primary
@Bean
public FreeMarkerConfigurationFactoryBean factoryBean() {
FreeMarkerConfigurationFactoryBean bean=new FreeMarkerConfigurationFactoryBean();
bean.setTemplateLoaderPath("classpath:/templates");
return bean;
}
}
Now, design your template file. under resources/template
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Oodles Technologies</title>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" valign="top" bgcolor="#838383"
style="background-color: #838383;"><br> <br>
<table width="600" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" valign="top" bgcolor="#d3be6c"
style="background-color: #d3be6c; font-family: Arial, Helvetica, sans-serif; font-size: 13px; color: #000000; padding: 0px 15px 10px 15px;">
<div style="font-size: 48px; color:black;">
<b>Payment Advice</b>
</div>
<div style="float:left; text-align:left;">
Deat Shipper,<br/><br/>
Thank you for Booking with Transport Exchange.<br/>
<br/>
Please find the details for the payment for Load ID <b>${loadId} </b>
<b>${loadType}</b> of Rs
<b>${amount}</b> as <b>{$name}</b> for Booking <b>${date}</b>.
<br/><br/>
<b>Transporter Details</b>
<br/><br/>
<table width="200" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
Transporter
</td>
<td> : ${name} </td>
</tr>
<tr>
<td>
Address
</td>
<td> : ${address} </td>
</tr>
<tr>
<td>
PAN
</td>
<td> : ${pan} </td>
</tr>
<tr>
<td>
GST
</td>
<td> : ${gst} </td>
</tr>
</table>
<br/><br/>
<b>Bank Details</b>
<br/><br/>
<table width="200" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
Account Number
</td>
<td> : ${accountNumber} </td>
</tr>
<tr>
<td>
IFSC Code
</td>
<td> : ${ifsc} </td>
</tr>
<tr>
<td>
Account Holder Name
</td>
<td> : ${acoountHolder} </td>
</tr>
</table>
<br/> <br/>
Kindly make the payment to the above details to start the trip.
<br/><br/>
Please contact TE Customer Service +91 xxxxxxxxxx/+91 xxxxxxxxxxxx, if you have received incorrect / transaction was not successful.
<br/><br/>
Assuring you of our best services.
<br/><br/>
Regards,<br/>
Transport Exchange<br/>
Service Department <br/>
</div>
</td>
</tr>
</table> <br/> <br/></td>
</tr>
</table>
</body>
</html>
Next, generate dto classes for request and response.
MailRequest.java
package com.techreloded.email.api.dto;
import lombok.Data;
@Data
public class MailRequest {
private String name;
private String loadId;
private String laodType;
private String amount;
private String date;
private String address;
private String gst;
private String accountNumber;
private String ifsc;
private String accountHolder;
private String pan;
private String to;
private String from;
private String subject;
}
package com.techreloded.email.api.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MailResponse {
private String message;
private boolean status;
}
Add Controller class
AppController.java
package com.techreloded.email.api.controller;
import com.javatechie.email.api.dto.MailRequest;
import com.javatechie.email.api.dto.MailResponse;
import com.javatechie.email.api.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class AppController {
@Autowired
private EmailService service;
@PostMapping("/sendingEmail")
public MailResponse sendEmail(@RequestBody MailRequest request) {
Map<String, Object> model = new HashMap<>();
model.put("name", request.getName());
model.put("loadType", request.getLoad());
model.put("loadId", request.getLoadId());
model.put("amount", request.getAmount());
model.put("date", request.getDate());
model.put("address", request.getAddress());
model.put("gst", request.getGst());
model.put("pan", request.getPan());
model.put("accountNumber", request.getAccountNumber());
model.put("ifsc", request.getIfsc());
model.put("accountNumber", request.getAccountNumber());
return service.sendEmail(request, model);
}
}
package com.techreloded.email.api.service;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import com.javatechie.email.api.dto.MailRequest;
import com.javatechie.email.api.dto.MailResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@Service
public class EmailService {
@Autowired
private JavaMailSender sender;
@Autowired
private Configuration config;
public MailResponse sendEmail(MailRequest request, Map<String, Object> model) {
MailResponse response = new MailResponse();
MimeMessage message = sender.createMimeMessage();
try {
// set mediaType
MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
// add attachment
helper.addAttachment("logo.png", new ClassPathResource("logo.png"));
Template t = config.getTemplate("email-template.ftl");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
helper.setTo(request.getTo());
helper.setText(html, true);
helper.setSubject(request.getSubject());
helper.setFrom(request.getFrom());
sender.send(message);
response.setMessage("mail send to : " + request.getTo());
response.setStatus(Boolean.TRUE);
} catch (MessagingException | IOException | TemplateException e) {
response.setMessage("Mail Sending failure : "+e.getMessage());
response.setStatus(Boolean.FALSE);
}
return response;
}
}
And here is my Main Class
package com.techreloded.email.api;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.javatechie.email.api.dto.MailRequest;
import com.javatechie.email.api.dto.MailResponse;
import com.javatechie.email.api.service.EmailService;
@SpringBootApplication
public class SpringBootEmailFreemarkerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootEmailFreemarkerApplication.class, args);
}
}
Now, hit the controller with proper payload you should receive email in you gmail inbox. Hope you found this blog helpful. Thanks.
Comments
Post a Comment