Home > Software engineering >  ktor send email with html template
ktor send email with html template

Time:06-09

I am wondering what is the correct way of sending HTML templates with ktor via email. This answer Sending Emails From Ktor Application can help inline HTML, or simple string but not hbs or other templates which can be used in ktor.

email service will work, but I do want to use a template. And doing it via MustacheContent will not work

package com.meet.utils.email

import com.meet.utils.Constants
import org.apache.commons.mail.DefaultAuthenticator
import org.apache.commons.mail.HtmlEmail

fun sendForgotPasswordEmail(token: String, emailTo: String) {
    val email = HtmlEmail()
    email.hostName = "smtp.sendgrid.net"
    email.setSmtpPort(587)
    email.setAuthenticator(
        DefaultAuthenticator(
            "apikey",
            "API_KEY"
        )
    )
    email.isSSLOnConnect = true
    email.setFrom(Constants.EMAIL_FROM)
    email.subject = "Forgot Password"
    email.setHtmlMsg("<html><body><div style='background:red;'>Hello</div></body></html>")
    email.addTo(emailTo)
    email.send()
}

What I want to do is

email.sendTemplate(MustacheContent("forgotPassword.hbs", mapOf("token" to token)))

how I can send this? resources/templates/reset.hbs

<html>
  <body>
    <h1>Hello</h1>
    <p>Please visit the link below to reset your password</p>
    <a href="http://localhost:3000?token={{token}}">Reset your password</a>
  </body>
</html>

CodePudding user response:

You can compile and render a template via a Mustache factory to get an HTML string. Here is an example:

val factory = DefaultMustacheFactory("templates")
embeddedServer(Netty, port = 3333) {
    install(Mustache) {
        mustacheFactory = factory
    }

    routing {
        post("/") {
            val content = MustacheContent("forgotPassword.hbs", mapOf("token" to "my-token"))
            val writer = StringWriter()
            factory.compile(content.template).execute(writer, content.model)
            val html = writer.toString()
            // Send email with an HTML
        }
    }

}.start(wait = true)
  • Related