kotlin发邮件

1. 依赖

dependencies{
    // https://mvnrepository.com/artifact/javax.mail/mail
    implementation("javax.mail:mail:1.5.0-b01")
}

2. 实现

import java.util.*
import javax.activation.DataHandler
import javax.activation.FileDataSource
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart

fun main() {
    val account = "你的账号@qq.com"
    val password = "填邮箱密码或key"
    val personal = "发信使用的昵称"
    val to = "接收账号@qq.com"
    val props = mapOf(
// 认证
        "mail.smtp.auth" to "true",
// smtp服务器
        "mail.smtp.host" to "smtp.qq.com",
// smtp端口
        "mail.smtp.port" to "587",
    )
    val subject = "主题"
    val text = "内容"
    val html= "<h5>这是HTML</h5>"
    val filePath1 = """D:\图片\aaa.jpg"""
    val filePath2 = """D:\图片\0.png"""
    val filename = "绝命响应.png"

    val properties = Properties().apply { putAll(props) }

    val authenticator = object : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(account, password)
        }
    }

    val mailSession = Session.getInstance(properties, authenticator)

    val textMessage = MimeMessage(mailSession).apply {
        setFrom(InternetAddress(account, personal, "UTF-8"))
        setRecipient(Message.RecipientType.TO, InternetAddress(to))
        setSubject(subject)

        setText(text)
    }

    val htmlMessage = MimeMessage(mailSession).apply {
        setFrom(InternetAddress(account, personal, "UTF-8"))
        setRecipient(Message.RecipientType.TO, InternetAddress(to))
        setSubject(subject)

        setContent(html, "text/html")
    }

    val multipartMessage = MimeMessage(mailSession).apply {
        setFrom(InternetAddress(account, personal, "UTF-8"))
        setRecipient(Message.RecipientType.TO, InternetAddress(to))
        setSubject(subject)

        val multipart = MimeMultipart().apply {
            addBodyPart(MimeBodyPart().apply {
                setContent(html, "text/html")
            })
// 若setContent设置为HTML,则前后都无法显示setText中内容
//            addBodyPart(MimeBodyPart().apply { setText("this is a text") })

            addBodyPart(MimeBodyPart().apply { attachFile(filePath1) })

            addBodyPart(MimeBodyPart().apply {
                val source=FileDataSource(filePath2)
                dataHandler = DataHandler(source)
                fileName=filename
            })
        }

        setContent(multipart)
    }


//    Transport.send(textMessage)
//    Transport.send(htmlMessage)
    Transport.send(multipartMessage)

}
上一篇:SpringBoot之文件上传


下一篇:包机制