This Spring Boot Freemarker Email Template tutorial walks you through sending the email with freemarker template using Spring Boot. This topic will cover, how to setup maven project, email service implementation, load freemarker template, Spring Boot application configuration.
If you are newbie on the Spring Boot and Freemaker, you may refer to the post Spring Boot FreeMarker Hello World Example before starting this topic.
Other interesting posts you may like
Spring Boot Freemarker Email Template
Let’s begin:
Project structure
In this Spring Boot Freemarker Email Template tutorial, we will create a project with directory structure like below
Maven Dependencies
To create Spring Boot Freemarker Email Template example, you need to add dependencies into pom.xml file like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode</groupId> <artifactId>spring-boot-freemarker-email-template</artifactId> <packaging>jar</packaging> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</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-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!-- Package as an executable jar/war --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> |
Mail Service implementation
Our Mail service is implemented such as the below class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.javabycode.service; import java.util.Properties; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import com.javabycode.model.Mail; import freemarker.template.Configuration; import freemarker.template.Template; @Service public class MailService { @Autowired private JavaMailSender sender; @Autowired private Configuration freemarkerConfig; public void sendEmail(Mail mail) throws Exception { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); // Using a subfolder such as /templates here freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates"); Template t = freemarkerConfig.getTemplate("email-template.ftl"); String text = FreeMarkerTemplateUtils.processTemplateIntoString(t, mail.getModel()); helper.setTo(mail.getMailTo()); helper.setText(text, true); helper.setSubject(mail.getMailSubject()); sender.send(message); } } |
Dig deeper: The mail service is annotated as “mailService” using @Service annotation. Beside, we use @Autowired annotation to autowire JavaMailSender and free marker configuration beans.
Spring MimeMessageHelper class provides support for HTML text content, inline elements such as images, and typical mail attachments. It also takes care of populating MimeMessage object.
processTemplateIntoString() method replaces the placeholders values with model attribute values and populates email contents from FreeMarker template.
JavaMailSender.send() method to send populated MIME message.
Configuration properties
1 2 3 4 5 6 7 |
spring.main.banner-mode=off #email email.host=smtp.gmail.com email.port=587 email.username=javabycode@gmail.com email.password=password |
Fetch email properties into EmailProperties bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package com.javabycode.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties("email") public class EmailProperties { private String host; private String port; private String username; private String password; public void setHost(String host) { this.host = host; } public String getHost() { return host; } public void setPort(String port) { this.port = port; } public String getPort() { return port; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } } |
Setup Mail sender
Create mail sender using Spring JavaMailSenderImpl class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.javabycode.config; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.stereotype.Component; @Component @Configuration public class EmailConfig { @Autowired EmailProperties emailProperties; @Bean public JavaMailSender getMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(emailProperties.getHost()); mailSender.setPort(Integer.parseInt(emailProperties.getPort())); mailSender.setUsername(emailProperties.getUsername()); mailSender.setPassword(emailProperties.getPassword()); Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.starttls.enable", "true"); javaMailProperties.put("mail.smtp.auth", "true"); javaMailProperties.put("mail.transport.protocol", "smtp"); javaMailProperties.put("mail.debug", "true"); mailSender.setJavaMailProperties(javaMailProperties); return mailSender; } } |
Mail Pojo
This is simple pojo class which contains different email attributes like mailFrom, mailTo, mailCc, mailBcc, mailSubject, mailContent, contentType, attachments and model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class Mail { private String mailFrom; private String mailTo; private String mailCc; private String mailBcc; private String mailSubject; private String mailContent; private String contentType; private List < Object > attachments; private Map < String, Object > model; public Mail() { contentType = "text/plain"; } // getter and setter } |
FreeMarker Email Template
Create freeMarker email template file (email-template.ftl) under folder /resources/templates/ along with respected placeholders variables.
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <head></head> <body> <p>Dear ${firstName} ${lastName},</p> <p>Sending Email using Spring Boot with <b>FreeMarker template !!!</b></p> <p>Thanks</p> <p>${signature}</p> <p>${location}</p> </body> </html> |
Create Spring Boot Application
We create Spring Boot Application class which implements CommandLineRunner and has the main method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package com.javabycode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.javabycode.model.Mail; import com.javabycode.service.MailService; import static java.lang.System.exit; import java.util.HashMap; import java.util.Map; @SpringBootApplication public class SpringBootEmailApplication implements CommandLineRunner { @Autowired MailService mailService; public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootEmailApplication.class, args); } @Override public void run(String... args) throws Exception { Mail mail = new Mail(); mail.setMailFrom("javabycode@gmail.com"); mail.setMailTo("davidpham@gmail.com"); mail.setMailSubject("Spring Boot - Email with FreeMarker template"); Map<String, Object> model = new HashMap<String, Object>(); model.put("firstName", "David"); model.put("lastName", "Pham"); model.put("location", "Columbus"); model.put("signature", "www.javabycode.com"); mail.setModel(model); mailService.sendEmail(mail); System.out.println("Done!"); exit(0); } } |
Run the Spring Boot Application
Foremost, we need to go to project directory in console, then package and run it using command line.
1 2 3 |
mvn package java -jar target/spring-boot-freemarker-email-template-1.0.jar |
It sends email to specified recipients. Here is the email which i have received
That’s all on the Spring Boot Freemarker Email Template tutorial.
References
Spring Boot FreeMarker
Download complete source code, click link below
spring-boot-freemarker-email-template-1.zip (840 downloads)
Hi Im getting below error,
501 5.5.4 Invalid Email address
DEBUG SMTP: got response code 501, with response: 501 5.5.4 Invalid Email address
RSET
250 2.0.0 Resetting
DEBUG SMTP: MessagingException while sending, THROW:
com.sun.mail.smtp.SMTPSendFailedException: 501 5.5.4 Invalid Email address
;
nested exception is:
com.sun.mail.smtp.SMTPSenderFailedException: 501 5.5.4 Invalid Email address
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2267)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1758)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1257)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:448)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:345)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
at com.javabycode.service.MailService.sendEmail(MailService.java:40)
at com.javabycode.SpringBootEmailApplication.run(SpringBootEmailApplication.java:40)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:760)
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:747)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
at com.javabycode.SpringBootEmailApplication.main(SpringBootEmailApplication.java:22)
Caused by: com.sun.mail.smtp.SMTPSenderFailedException: 501 5.5.4 Invalid Email address
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1767)
… 13 more
QUIT
221 2.0.0 BLU437-SMTP9.smtp.hotmail.com Service closing transmission channel
2017-08-27 16:48:27 ERROR o.s.boot.SpringApplication – Application startup failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:779)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:760)
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:747)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
at com.javabycode.SpringBootEmailApplication.main(SpringBootEmailApplication.java:22)
Caused by: org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 501 5.5.4 Invalid Email address
;
nested exception is:
com.sun.mail.smtp.SMTPSenderFailedException: 501 5.5.4 Invalid Email address
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:474)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:345)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
at com.javabycode.service.MailService.sendEmail(MailService.java:40)
at com.javabycode.SpringBootEmailApplication.run(SpringBootEmailApplication.java:40)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776)
… 6 common frames omitted
Your email host is not configured properly, i guess