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



如何用Java(或Kotlin(编写mime电子邮件?我不知道如何使用javax.mail.internet.MimeMessage,因为我没有smtp,但有https端点(使用Mailgun服务(。

下面的代码发送多部分/表单数据请求,但在目标邮箱中只收到纯文本(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消息的方法,然后将其作为多部分/表单数据发送。看起来不太干净,但至少它有效:

在原始代码中,而不是:

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()

相关内容

  • 没有找到相关文章