Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ktor send email with html template

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading