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

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

    val email = HtmlEmail()
    email.hostName = ""
    email.setAuthenticator(DefaultAuthenticator(senderEmail, password))
    email.isSSLOnConnect = true
    email.subject = "Test email with inline image sent using Kotlin"
    val kotlinLogoURL = URL("")
    val cid = email.embed(kotlinLogoURL, "Kotlin logo")
    email.setHtmlMsg("<html><h1>Kotlin logo</h1><img src=\"cid:$cid\"></html>")

Continue reading


Simple mail sending in Java via Gmail/SMTP

If you happen to have Gmail account, and you wish to use it to send mail for any reason to any recipient, that can be done quite easilly.

Adding dependency to commons-email

I suggest using Maven or Gradle to deal with required dependency to commons-email artifact (I’m using Maven for demo) in order to reduce complexity of finding correct jar(s).

Continue reading