How to use freemarker to send email using springboot
3 answers
There is a "Configuration" object that you can get as a bean:
Here is the code:
package your.package;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import freemarker.template.Configuration;
import freemarker.template.Template;
@Controller
public class MailTemplate {
@Autowired
Configuration configuration;
@RequestMapping("/test")
public @ResponseBody String test2() throws Exception {
// prepare data
Map<String, String> data = new HashMap<>();
data.put("name", "Max Mustermann");
// get template
Template t = configuration.getTemplate("test.html");
String readyParsedTemplate = FreeMarkerTemplateUtils
.processTemplateIntoString(t, data);
// do what ever you want to do with html...
// just for testing:
return readyParsedTemplate;
}
}
+11
source to share
First of all, you should define the email content using a Freemarker template like
<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>
Then create an email service that processes the email template and returns my message object like
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);
}
}
However, a general working example does not fit here. You can refer to the completed tutorial Spring Boot Freemarker Email Template
Hope this helps!
+2
source to share
DVController.java
package com.dv;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import freemarker.template.Configuration;
import freemarker.template.Template;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
@RestController
public class DVController {
//Autowired Configuration class to get instance
@Autowired
private Configuration freemarkerConfig;
private static Logger logger = LoggerFactory.getLogger(DVController.class);
private String host = "SMTP sever address";
private Integer port = SMTP server port number;
private String userName = "Your user name";
private String password = "Your account password";
public Session createSMTPServerSession() throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
// SSL SECURITIES CERTIFICATION
props.put("mail.smtp.startssl.enable", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.ssl.enable", "true");
props.setProperty("mail.smtp.ssl.required", "true");
// Create the connection session after authentication
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
return session;
}
@RequestMapping(method=RequestMethod.GET,value="sendemail")
public boolean sentMail() throws Exception {
//Get session connection
Session session = createSMTPServerSession();
//Create MimeMessage instance for communication
MimeMessage message = new MimeMessage(session);
//Set User Name in which id the email sent to client
message.setFrom(new InternetAddress(userName));
//Get the instance from autowired variable and load the template in instance and set the path where ftl file available
freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/freemarker");
//Create a map object and set the data which is send dynamically to the FTL template file
Map<String, String> ftlProperties = new HashMap<String,String>();
ftlProperties.put("header", "DEVELOPER VILLAGE");
ftlProperties.put("userName", "Developer village");
ftlProperties.put("message", "This is the testing ftl from message developer village email.");
//Instance the FTL file with the name
Template t = freemarkerConfig.getTemplate("developer_village.ftl");
//Set the FTL properties
String text = FreeMarkerTemplateUtils.processTemplateIntoString(t,ftlProperties);
message.addRecipient(Message.RecipientType.TO, new InternetAddress("Write the email address,want to send email"));
//Set the email type in this case it html syntax
message.setContent(text, "text/html");
//Set the email header
message.setSubject("Testing email from Developer Village.");
Transport.send(message);
return true;
}
}
For full details, visit https://developervillage.blogspot.com/2019/05/send-ftl-in-email-using-spring-boot-in.html
0
source to share