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>")

Application input

There are three input parameters required:

  • your Gmail address
  • your Gmail password
  • recipient email address

Application dependencies

Application requires having 3 libs on your classpath. You can either use build tool to help you automate that, or, in case you don’t want to depend on that – just download the libs listed below, and put them in lib directory.

activation-1.1.1.jar , commons-email-1.4.jarjavax.mail-1.5.2.jar

Application layout

Application requires the following filesystem structure:

+ project-root
    + scripts
        + mail
            - MailSender.kt
    + lib
        - activation-1.1.1.jar
        - commons-email-1.4.jar
        - javax.mail-1.5.2.jar

Compiling application (run from project root)

kotlinc \
 -cp lib/activation-1.1.1.jar:lib/commons-email-1.4.jar:lib/javax.mail-1.5.2.jar \
 scripts/mail/MailSender.kt -include-runtime -d mailSender.jar

Running application (run from project root)

java -cp "mailSender.jar:lib/*" \
     mail.MailSenderKt \

In case you have enabled two factor authentication using your gmail account, you need to create application password here and use that as a password in command above.

Mail contain header and logo shown below will be delivered to mail recipient you passed to java command above.kotlin-logo-mail

In case you liked this post and you’re interested in getting more content – don’t forget to subscribe!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s