I'm trying to send an inline email using spring boot and thymeleaf. I have added new template file "test-email.html"
And I have following bean configurations
@Qualifier("emailSender")
@Autowired
private val templateEngine: SpringTemplateEngine? = null
@Bean(name = ["emailSender"])
fun springTemplateEngine(): SpringTemplateEngine? {
val templateEngine = SpringTemplateEngine()
templateEngine.addTemplateResolver(htmlTemplateResolver())
return templateEngine
}
@Bean
fun htmlTemplateResolver(): SpringResourceTemplateResolver? {
val emailTemplateResolver = SpringResourceTemplateResolver()
emailTemplateResolver.prefix = "/templates/email/"
emailTemplateResolver.suffix = ".html"
emailTemplateResolver.templateMode = TemplateMode.HTML
emailTemplateResolver.characterEncoding = StandardCharsets.UTF_8.name()
return emailTemplateResolver
}
Following functions is used to send the resolve template and send email.
fun sendTemplateMessage(to: String, subject: String, text: String) {
val mimeMessage: MimeMessage? = emailSender?.createMimeMessage()
val helper = mimeMessage?.let { MimeMessageHelper(it, "utf-8") }
val context = Context()
context.setVariable("msg", "This is test message")
val htmlMsg = templateEngine!!.process("test-email", context)
helper?.setText(htmlMsg, true)
helper?.setTo(to)
helper?.setSubject(subject)
emailSender?.send(mimeMessage)
}
But this gives a FileNotFound exception.
Caused by: java.io.FileNotFoundException: ReactiveWebContext resource [/templates/email/test-email.html] cannot be opened because it does not exist
How can I provide template file path to the templating engine?
classpath:
in the value ofemailTemplateResolver.prefix
. So the final value would be like"classpath:/templates/email/"
. – Saurabh