Sending email

suggest change

Kotlin on the JVM has no email client in its standard library. The usual choices are:


Dependencies (Gradle)

Since Jakarta EE 9 the package is jakarta.mail, not javax.mail. Don't mix the old javax.mail / com.sun.mail artifacts with the new ones.

dependencies {
    implementation("jakarta.mail:jakarta.mail-api:2.1.5")    // API (jakarta.mail.*)
    implementation("org.eclipse.angus:angus-mail:2.0.5")     // implementation (SMTP provider)
}

Sending a plain-text email over SMTP with STARTTLS

Most providers take submissions on port 587 with STARTTLS: the connection starts unencrypted and is upgraded to TLS before you authenticate.

import jakarta.mail.Authenticator
import jakarta.mail.Message
import jakarta.mail.PasswordAuthentication
import jakarta.mail.Session
import jakarta.mail.Transport
import jakarta.mail.internet.InternetAddress
import jakarta.mail.internet.MimeMessage
import java.util.Date
import java.util.Properties

fun smtpSession(host: String, port: Int, user: String, password: String): Session {
    val props = Properties().apply {
        put("mail.smtp.host", host)
        put("mail.smtp.port", port.toString())
        put("mail.smtp.auth", "true")
        put("mail.smtp.starttls.enable", "true")
        put("mail.smtp.starttls.required", "true")     // refuse to send in clear text
        put("mail.smtp.ssl.checkserveridentity", "true")
        put("mail.smtp.connectiontimeout", "10000")    // ms; default is infinite
        put("mail.smtp.timeout", "10000")
        put("mail.smtp.writetimeout", "10000")
    }
    return Session.getInstance(props, object : Authenticator() {
        override fun getPasswordAuthentication() = PasswordAuthentication(user, password)
    })
}

fun main() {
    val session = smtpSession(
        host = "smtp.example.com",
        port = 587,
        user = System.getenv("SMTP_USER") ?: error("SMTP_USER not set"),
        password = System.getenv("SMTP_PASSWORD") ?: error("SMTP_PASSWORD not set"),
    )

    val message = MimeMessage(session).apply {
        setFrom(InternetAddress("noreply@example.com", "Example App"))
        setRecipients(Message.RecipientType.TO, InternetAddress.parse("alice@example.com, bob@example.com"))
        setRecipients(Message.RecipientType.CC, InternetAddress.parse("team@example.com"))
        replyTo = arrayOf(InternetAddress("support@example.com"))
        setSubject("Your report is ready", "UTF-8")
        setText("Hi,\n\nYour weekly report is ready.\n\nCheers", "UTF-8")
        sentDate = Date()
    }

    Transport.send(message)
    println("Sent message ${message.messageID}")
}

Notes:


HTML email with a plain-text fallback

Send HTML as a multipart/alternative that also carries a plain-text version. Text-only clients show the text part, and spam filters score messages better when both are present.

import jakarta.mail.internet.MimeBodyPart
import jakarta.mail.internet.MimeMultipart

fun alternativeBody(text: String, html: String): MimeMultipart =
    MimeMultipart("alternative").apply {
        // Order matters: least preferred first, most preferred last
        addBodyPart(MimeBodyPart().apply { setText(text, "UTF-8") })
        addBodyPart(MimeBodyPart().apply { setContent(html, "text/html; charset=UTF-8") })
    }

val name = "Alice"
message.setContent(
    alternativeBody(
        text = "Hello $name, welcome aboard!",
        html = """
            <html><body>
              <h1>Hello $name</h1>
              <p>Welcome <b>aboard</b>!</p>
            </body></html>
        """.trimIndent(),
    )
)

If you interpolate user data into HTML, escape it first. Otherwise a name like <script> ends up as markup in the email.


Attachments and inline images

Attachments go in a multipart/mixed container. The message body (text or alternative) is its first part:

import jakarta.mail.Part
import java.io.File

fun messageWithAttachments(
    session: Session,
    text: String,
    html: String,
    attachments: List<File>,
): MimeMessage {
    val mixed = MimeMultipart("mixed")

    // 1. Body: text + HTML alternatives wrapped in a body part
    mixed.addBodyPart(MimeBodyPart().apply { setContent(alternativeBody(text, html)) })

    // 2. File attachments; attachFile() sets the file name and guesses the MIME type
    for (file in attachments) {
        mixed.addBodyPart(MimeBodyPart().apply { attachFile(file) })
    }

    return MimeMessage(session).apply { setContent(mixed) }
}

To attach bytes from memory, such as a generated PDF, use a DataSource:

import jakarta.activation.DataHandler
import jakarta.mail.util.ByteArrayDataSource

val pdfBytes: ByteArray = generateInvoicePdf()
val pdfPart = MimeBodyPart().apply {
    dataHandler = DataHandler(ByteArrayDataSource(pdfBytes, "application/pdf"))
    fileName = "invoice-2026-10.pdf"
    disposition = Part.ATTACHMENT
}

An inline image goes into a multipart/related part, and the HTML refers to it by Content-ID with a cid: URL:

val related = MimeMultipart("related").apply {
    addBodyPart(MimeBodyPart().apply {
        setContent("""<p>Hi!</p><img src="cid:logo">""", "text/html; charset=UTF-8")
    })
    addBodyPart(MimeBodyPart().apply {
        attachFile(File("logo.png"))
        contentID = "<logo>"
        disposition = Part.INLINE
    })
}

Sending many messages over one connection

Transport.send() reconnects for every message. For a batch, open one Transport and reuse it. Transport is AutoCloseable, so use closes it for you:

fun sendBatch(session: Session, messages: List<MimeMessage>) {
    session.getTransport("smtp").use { transport ->
        transport.connect()   // uses host/port from properties and the session's Authenticator
        for (msg in messages) {
            msg.saveChanges()  // Transport.send() does this automatically; sendMessage() doesn't
            transport.sendMessage(msg, msg.allRecipients)
        }
    }
}

Using it from coroutines

Jakarta Mail is blocking I/O. Inside coroutines, move the call to Dispatchers.IO so it doesn't block a thread the coroutine scheduler needs:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

suspend fun sendAsync(message: MimeMessage) = withContext(Dispatchers.IO) {
    Transport.send(message)
}

Simple Java Mail

Simple Java Mail wraps Jakarta Mail in a fluent builder. It handles multipart structure, attachments, embedded images, TLS modes and connection pooling for you:

// implementation("org.simplejavamail:simple-java-mail:8.12.6")
import org.simplejavamail.api.mailer.config.TransportStrategy
import org.simplejavamail.email.EmailBuilder
import org.simplejavamail.mailer.MailerBuilder
import java.io.File

val email = EmailBuilder.startingBlank()
    .from("Example App", "noreply@example.com")
    .to("Alice", "alice@example.com")
    .withSubject("Your invoice")
    .withPlainText("Your invoice is attached.")
    .withHTMLText("<p>Your invoice is <b>attached</b>.</p>")
    .withAttachment("invoice.pdf", File("invoice.pdf").readBytes(), "application/pdf")
    .buildEmail()

// Build the mailer once and reuse it; it manages a connection pool
val mailer = MailerBuilder
    .withSMTPServer("smtp.example.com", 587, System.getenv("SMTP_USER"), System.getenv("SMTP_PASSWORD"))
    .withTransportStrategy(TransportStrategy.SMTP_TLS)   // STARTTLS; use SMTPS for port 465
    .withSessionTimeout(10_000)
    .buildMailer()

mailer.sendMail(email)

Sending through an HTTP API

Transactional email providers also offer REST APIs. These often work better than SMTP in cloud environments, where outbound port 25/587 is frequently blocked. You also get delivery tracking and templates. This example uses SendGrid's v3 API with the JDK's built-in HttpClient and kotlinx.serialization:

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse

@Serializable data class Address(val email: String, val name: String? = null)
@Serializable data class Personalization(val to: List<Address>)
@Serializable data class Content(val type: String, val value: String)
@Serializable data class SendRequest(
    val personalizations: List<Personalization>,
    val from: Address,
    val subject: String,
    val content: List<Content>,
)

fun sendViaApi(to: String, subject: String, text: String, html: String) {
    val body = Json.encodeToString(
        SendRequest(
            personalizations = listOf(Personalization(listOf(Address(to)))),
            from = Address("noreply@example.com", "Example App"),
            subject = subject,
            content = listOf(Content("text/plain", text), Content("text/html", html)),
        )
    )
    val request = HttpRequest.newBuilder(URI("https://api.sendgrid.com/v3/mail/send"))
        .header("Authorization", "Bearer ${System.getenv("SENDGRID_API_KEY")}")
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(body))
        .build()

    val response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString())
    check(response.statusCode() == 202) { "Send failed: ${response.statusCode()} ${response.body()}" }
}

Testing with a local SMTP server

During development, point the app at a local catch-all server such as Mailpit. Messages go nowhere real, and you can view them in a web UI:

docker run --rm -p 1025:1025 -p 8025:8025 axllent/mailpit
# SMTP on localhost:1025 (no auth, no TLS), web UI on http://localhost:8025

For Mailpit, configure the session with mail.smtp.host=localhost, mail.smtp.port=1025, and set mail.smtp.auth and mail.smtp.starttls.enable to false.

In automated tests, GreenMail runs an in-process SMTP server. Version 2.x uses jakarta.mail:

// testImplementation("com.icegreen:greenmail-junit5:2.1.14")
import com.icegreen.greenmail.junit5.GreenMailExtension
import com.icegreen.greenmail.util.GreenMailUtil
import com.icegreen.greenmail.util.ServerSetupTest
import jakarta.mail.Message
import jakarta.mail.Session
import jakarta.mail.Transport
import jakarta.mail.internet.InternetAddress
import jakarta.mail.internet.MimeMessage
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
import java.util.Properties

class EmailTest {
    @JvmField
    @RegisterExtension
    val greenMail = GreenMailExtension(ServerSetupTest.SMTP)   // SMTP on localhost:3025

    @Test
    fun `sends welcome email`() {
        val props = Properties().apply {
            put("mail.smtp.host", "localhost")
            put("mail.smtp.port", ServerSetupTest.SMTP.port.toString())
        }
        val msg = MimeMessage(Session.getInstance(props)).apply {
            setFrom(InternetAddress("noreply@example.com"))
            setRecipient(Message.RecipientType.TO, InternetAddress("alice@example.com"))
            subject = "Welcome"
            setText("Hello Alice", "UTF-8")
        }
        Transport.send(msg)

        val received = greenMail.receivedMessages
        assertEquals(1, received.size)
        assertEquals("Welcome", received[0].subject)
        assertEquals("Hello Alice", GreenMailUtil.getBody(received[0]).trim())
    }
}

In unit tests, put sending behind an interface (interface EmailSender { fun send(...) }) and replace it with a fake or mock. Keep real SMTP round-trips for a few integration tests.


Best practices

  1. Keep credentials out of code. Read SMTP passwords and API keys from environment variables or a secret store. With Gmail and Microsoft 365, use app passwords or OAuth2 (XOAUTH2), not the account password.
  2. Always use TLS (starttls.required or port 465) and keep server identity checks enabled.
  3. Send from a domain you control, with SPF, DKIM and DMARC records configured. Without them, providers will put your mail in spam or reject it.
  4. Don't send in the request path. Put messages on a queue or background job and retry on transient failures (MessagingException, HTTP 429/5xx) with backoff.
  5. Validate addresses with InternetAddress(addr).validate() before accepting them from users. It only checks syntax; confirm ownership with a verification email.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents