Parsing E-mail message with Kotlin (Java)


Because it’s hard to use JavaMail alone, use Apache Commons Email.

build.gradle

dependencies {
  compile 'javax.mail:mail:1.4.7'
  compile 'org.apache.commons:commons-email:1.5'
}

Kotlin

import org.apache.commons.mail.util.MimeMessageParser
import java.io.ByteArrayInputStream
import java.io.IOException
import java.util.Properties
import javax.mail.MessagingException
import javax.mail.Session
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage

...

fun parse(rawMimeMessage: String): MailData? =
    ByteArrayInputStream(rawMimeMessage.toByteArray()).use {
        try {
            val session = Session.getDefaultInstance(Properties())
            val parser = MimeMessageParser(MimeMessage(session, it))
            parser.parse()
            MailData(
                    parser.from,
                    parser.replyTo ?: parser.from,
                    parser.to.map { (it as InternetAddress).address },
                    parser.cc.map { (it as InternetAddress).address },
                    parser.bcc.map { (it as InternetAddress).address },
                    parser.subject,
                    parser.htmlContent,
                    parser.plainContent
            )
        } catch (ex: MessagingException) {
            logger.warn("parse error", ex)
            null
        } catch (ex: IOException) {
            logger.warn("parse error", ex)
            null
        }
    }

...

data class MailData(
    val from: String,
    val replyTo: String,
    val to: List<String>,
    val cc: List<String>,
    val bcc: List<String>,
    val subject: String,
    val htmlContent: String?,
    val textContent: String?
)

See also