1
votes

I'm trying to send an inline email using spring boot and thymeleaf. I have added new template file "test-email.html" enter image description here

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?

1
can you try after adding classpath: in the value of emailTemplateResolver.prefix. So the final value would be like "classpath:/templates/email/".Saurabh
@Saurabh Yes it worked!. ThanksRuchira
Let me add it as a answer then.Saurabh

1 Answers

2
votes

Add classpath: as prefix of your file path. The reason behind is that it will take the relative path from where the jar is deployed otherwise it will consider the given path as an absolute path.

So change your code as below:

@Bean
fun htmlTemplateResolver(): SpringResourceTemplateResolver? {
    val emailTemplateResolver = SpringResourceTemplateResolver()
    emailTemplateResolver.prefix = "classpath:/templates/email/"
    emailTemplateResolver.suffix = ".html"
    emailTemplateResolver.templateMode = TemplateMode.HTML
    emailTemplateResolver.characterEncoding = StandardCharsets.UTF_8.name()
    return emailTemplateResolver
}