Kotlin教程

kotlin发邮件

本文主要是介绍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)

}
这篇关于kotlin发邮件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!