我想知道通過電子郵件使用 ktor 發送 HTML 模板的正確方法是什么。這個答案 從 Ktor 應用程式發送電子郵件可以幫助行內 HTML,或簡單的字串,但不能幫助 hbs 或其他可在 ktor 中使用的模板。
電子郵件服務可以,但我確實想使用模板。并且通過 MustacheContent 來做這件事是行不通的
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()
}
我想做的是
email.sendTemplate(MustacheContent("forgotPassword.hbs", mapOf("token" to token)))
我怎么能發送這個?
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>
uj5u.com熱心網友回復:
您可以通過 Mustache 工廠編譯和呈現模板以獲取 HTML 字串。這是一個例子:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/487988.html
標籤:电子邮件 apache-commons 克托尔 HBs
