Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save gokman/1fe702c4e70542a19b207d88153e3269 to your computer and use it in GitHub Desktop.

Select an option

Save gokman/1fe702c4e70542a19b207d88153e3269 to your computer and use it in GitHub Desktop.
spring boot mail with freemarker template
1. in build.gradle file add below dependencies:
compile('org.springframework.boot:spring-boot-starter-mail:${springBootVersion}')
compile("org.springframework.boot:spring-boot-starter-freemarker:${springBootVersion}")
2. in application.properties file add freemarker configurations
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.template-loader-path=classpath:/templates/
3. add a sample template under templates folder with named "sample" like below:
<!doctype html>
<html>
<head></head>
<body>
<p style="font-weight: bold;">
Hi Test!!!
</p>
</body>
</html>
4. Finally prepare mail service to send mail
@Service
public class MailService {
@Autowired
private JavaMailSender sender;
@Autowired
private Configuration freemarkerConfig;
public void sendEmail(Mail mail, String templateName) throws Exception {
MimeMessagePreparator messagePreparator = mimeMessage -> {
// be careful about this line. adding UTF-8 to mime message helper important for character encoding
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");
Template t = freemarkerConfig.getTemplate(templateName,"UTF-8");
String text = FreeMarkerTemplateUtils.processTemplateIntoString(t, mail.getModel());
helper.setFrom(mail.getMailFrom());
helper.setTo(mail.getMailTo());
helper.setText(text, true);
helper.setSubject(mail.getMailSubject());
};
try {
sender.send(messagePreparator);
} catch (MailException e) {
throw new MailSendException(e.getMessage());
}
}
}
@cescoferraro
Copy link

thanksssss!

@SaminZou
Copy link

SaminZou commented Jan 8, 2021

good job !

@gokhankcmn
Copy link

thanksssss!

you are welcome :)

@gokhankcmn
Copy link

good job !

thanks...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment