Sending mail via gmail using Kotlin and commons-mail library

Continuing series of blog posts related to kotlin, today we’ll together make a sample application showing us how we could automate email sending – using kotlin. Example is quite simple, and surely – you can enhance it with own features. Application mostly demonstrates compact kotlin syntax, as well as full compatibility with Java or 3rd party libraries (in this case commons-mail library).

Let’s first take a look at our script:

package mail

import org.apache.commons.mail.DefaultAuthenticator
import org.apache.commons.mail.HtmlEmail
import java.net.URL

fun main(args: Array<String>) {
    val senderEmail = args[0]
    val password = args[1]
    val toMail = args[2]

    val email = HtmlEmail()
    email.hostName = "smtp.googlemail.com"
    email.setSmtpPort(465)
    email.setAuthenticator(DefaultAuthenticator(senderEmail, password))
    email.isSSLOnConnect = true
    email.setFrom(senderEmail)
    email.addTo(toMail)
    email.subject = "Test email with inline image sent using Kotlin"
    val kotlinLogoURL = URL("https://kotlinlang.org/assets/images/twitter-card/kotlin_800x320.png")
    val cid = email.embed(kotlinLogoURL, "Kotlin logo")
    email.setHtmlMsg("<html><h1>Kotlin logo</h1><img src=\"cid:$cid\"></html>")
    email.send()
}

Continue reading