以微软Office365的Outlook为例

引入依赖:

val mailVersion = "2.0.1"

implementation("com.sun.mail:jakarta.mail:$mailVersion")

代码:

fun main() {
    val from = ""
    val to = ""
    val host = "smtp.office365.com"
    val port = 587
    val username = ""
    val password = ""
    // 标题
    val subject = ""
    // 内容
    val content = ""
    // 类型
    val type = "text/plain"

    val props = Properties()
    props["mail.smtp.host"] = host
    props["mail.smtp.port"] = port
    props["mail.from"] = from
    props["mail.smtp.starttls.enable"] = true
    props["mail.smtp.auth"] = true
    val session = Session.getInstance(props, object : Authenticator() {
        override fun getPasswordAuthentication(): jakarta.mail.PasswordAuthentication {
            return jakarta.mail.PasswordAuthentication(username, password)
        }
    })

    val msg = MimeMessage(session)
    msg.setFrom(InternetAddress(from))
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))
    msg.subject = subject
    msg.sentDate = Date()
    msg.setContent(content, type)

    Transport.send(msg)
}
最后修改:2021 年 12 月 13 日
如果觉得我的文章对你有用,请随意赞赏