跳转至

Ktor

适用于 Ktor(Kotlin,JVM)应用的集成指南。Mailexam 通过 Jakarta Mail 作为 SMTP 服务器接入。

前置条件

  • Mailexam 账户,以及已创建并具备 SMTP 凭据的项目
  • JDK 17+ 及 Kotlin 1.9+。

从项目的欢迎邮件(或控制台)中复制:

  • YOUR_LOGIN — SMTP 登录名(例如 xxxxx);
  • YOUR_PASSWORD — SMTP 密码(与登录名成对的唯一凭据);
  • 主机 — YOUR_LOGIN.mailexam.cn登录名一致)。

1. 依赖

build.gradle.kts 片段:

plugins {
    kotlin("jvm") version "2.0.0"
    kotlin("plugin.serialization") version "2.0.0"
    application
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.ktor:ktor-server-core-jvm:3.0.0")
    implementation("io.ktor:ktor-server-netty-jvm:3.0.0")
    implementation("io.ktor:ktor-server-content-negotiation-jvm:3.0.0")
    implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:3.0.0")
    implementation("com.sun.mail:jakarta.mail:2.0.1")
}

application {
    mainClass.set("ApplicationKt")
}

通过 Ktor Project Generator 创建项目,或按下方结构手动搭建。

2. 环境变量

启动前设置变量(或在 IDE 中使用 .env):

MAILEXAM_LOGIN=YOUR_LOGIN
MAILEXAM_PASSWORD=YOUR_PASSWORD
MAILEXAM_PORT=587
MAIL_FROM=noreply@example.test

SMTP 主机:YOUR_LOGIN.mailexam.cn

发件人地址

MAIL_FROM 可以是任意测试地址——邮件进入 Mailexam,而非真实收件人。

备选端口

MAILEXAM_PORT=587

mail.smtp.starttls.enable=true

MAILEXAM_PORT=2525
MAILEXAM_PORT=25

mail.smtp.starttls.enable=false

3. 发送邮件

// src/main/kotlin/Mail.kt
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.Properties

object Mail {
    fun sendTest(to: String, subject: String, body: String) {
        val login = System.getenv("MAILEXAM_LOGIN")
            ?: error("MAILEXAM_LOGIN is not set")
        val password = System.getenv("MAILEXAM_PASSWORD")
            ?: error("MAILEXAM_PASSWORD is not set")
        val port = System.getenv("MAILEXAM_PORT")?.toInt() ?: 587
        val from = System.getenv("MAIL_FROM") ?: "noreply@example.test"

        val props = Properties().apply {
            put("mail.smtp.host", "$login.mailexam.cn")
            put("mail.smtp.port", port.toString())
            put("mail.smtp.auth", "true")
            put("mail.smtp.starttls.enable", (port == 587 || port == 2525).toString())
        }

        val session = Session.getInstance(props, object : Authenticator() {
            override fun getPasswordAuthentication(): PasswordAuthentication =
                PasswordAuthentication(login, password)
        })

        val message = MimeMessage(session).apply {
            setFrom(InternetAddress(from))
            setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))
            setSubject(subject, "UTF-8")
            setText(body, "UTF-8")
        }

        Transport.send(message)
    }
}

4. Ktor 路由

// src/main/kotlin/Application.kt
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable

@Serializable
data class SendRequest(
    val to: String = "user@example.test",
    val subject: String = "Ktor + Mailexam",
    val body: String = "来自 Ktor 的 Mailexam 测试",
)

fun main() {
    embeddedServer(Netty, port = 8080, host = "127.0.0.1", module = Application::module)
        .start(wait = true)
}

fun Application.module() {
    install(ContentNegotiation) {
        json()
    }

    routing {
        post("/mail/test") {
            val payload = call.receive<SendRequest>()

            withContext(Dispatchers.IO) {
                Mail.sendTest(
                    to = payload.to,
                    subject = payload.subject,
                    body = payload.body,
                )
            }

            call.respond(mapOf("status" to "ok"))
        }
    }
}

启动并验证:

./gradlew run
curl -X POST http://127.0.0.1:8080/mail/test \
  -H 'Content-Type: application/json' \
  -d '{"to":"user@example.test","subject":"测试","body":"你好"}'

邮件将出现在 Mailexam 控制台 → 您的项目 → 收件箱。

5. 本地开发与 CI

环境 建议
local IDE 运行配置中的环境变量
CI GitLab CI/CD Variables 中的密钥 MAILEXAM_LOGINMAILEXAM_PASSWORD

.gitlab-ci.yml 示例:

variables:
  MAILEXAM_LOGIN: $MAILEXAM_LOGIN
  MAILEXAM_PASSWORD: $MAILEXAM_PASSWORD
  MAILEXAM_PORT: "587"
  MAIL_FROM: "noreply@example.test"

集成测试后,通过 Mailexam API 验证投递。

6. 常见问题

TLS 或连接错误

  • mail.smtp.host 须为 {login}.mailexam.cnPasswordAuthentication 中的登录名 — 来自邮件。
  • 登录名和密码为同一项目的邮件成对凭据

事件循环阻塞

  • withContext(Dispatchers.IO) 中调用 Transport.send,如示例所示。

控制台中看不到邮件

  • 查看同一 Mailexam 项目的收件箱。
  • Mail.sendTest 抛出异常时检查 Ktor 日志。

参见