Search code examples
ktor

Sending Emails From Ktor Application


I'm currently creating my application using Ktor Netty Engine

I searched the docs for any feature to handle sending emails when a user sends a request to my server but found nothing.

post("/api/v1/auth") {
    // TODO send email when request is sent!
}

Solution

  • There is a java dependency available to be used in Ktor apache-email-commons

    implementation("org.apache.commons:commons-email:1.5")
    

    And then using an SMTP server e.g. Gmail:

    val email = SimpleEmail()
    email.hostName = "smtp.googlemail.com"
    email.setSmtpPort(465)
    email.setAuthenticator(DefaultAuthenticator("email-account", "account-password"))
    email.isSSLOnConnect = true
    email.setFrom("sender-email-account")
    email.subject = "email-subject"
    email.setMsg("message-content")
    email.addTo("target-email-address")
    email.send()