Created
June 30, 2017 10:18
-
-
Save gokman/1fe702c4e70542a19b207d88153e3269 to your computer and use it in GitHub Desktop.
spring boot mail with freemarker template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()); | |
| } | |
| } | |
| } | |
good job !
thanksssss!
you are welcome :)
good job !
thanks...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanksssss!