从头开始创建 mime 电子邮件(对于 Mailgun API)

Create mime email message from scratch (for Mailgun API)

如何在 Java(或 Kotlin)中编写 mime 电子邮件?我不明白如何使用 javax.mail.internet.MimeMessage 因为我没有 smtp,而是 https 端点(使用 Mailgun 服务)。

下面的代码发送 multipart/form-data 请求,但在目标邮箱中只收到纯文本(html 未呈现),没有“主题”和正确的“发件人”。

看来我必须将其嵌入到 mimeMessage 中,我将其作为表单数据附加。但是怎么办?

val fileMap: MultiValueMap<String, String> = LinkedMultiValueMap()
val contentDisposition = ContentDisposition
        .builder("form-data")
        .name("message")
        .filename("message.mime")
        .build()
fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString())

val mimeMessage = "<html>some <b>nice</b> html</html>".toByteArray() // <<-- How to build this properly?
val fileEntity = HttpEntity<ByteArray>(mimeMessage, fileMap)

val headers = HttpHeaders()
headers.contentType = MediaType.MULTIPART_FORM_DATA

val parts: MultiValueMap<String, Any> = LinkedMultiValueMap()
parts.add("file", fileEntity)
parts.add("from", mailProperties.fromAddress)
parts.add("to", email.to)
parts.add("subject", email.subject)

val requestEntity: HttpEntity<MultiValueMap<String, Any>> = HttpEntity(parts, headers)
val res = restTemplate.postForEntity("https://api.eu.mailgun.net/v3/mydomain.com/messages.mime", requestEntity, String::class.java)

好吧,我找到了编写正确的 MIME 消息然后将其作为 multipart/form-data 发送的方法。看起来不太干净,但至少可以用:

原代码中,代替:

val mimeMessage = "<html>some <b>nice</b> html</html>".toByteArray()

我做了以下事情:

val impl = JavaMailSenderImpl()
val msg = impl.createMimeMessage()
val helper = MimeMessageHelper(msg, true)
helper.setFrom(mailProperties.fromAddress)
helper.addTo(email.to)
helper.setSubject(email.subject)
helper.setText("<html>some <b>nice</b> html</html>", true)
val out = ByteArrayOutputStream()
helper.mimeMessage.writeTo(out)
val mimeMessage = out.toByteArray()