Reading message body

This commit is contained in:
dankito 2024-11-21 20:30:20 +01:00
parent 399581da78
commit 9aaa2f630c
3 changed files with 36 additions and 0 deletions

View File

@ -112,6 +112,7 @@ class MailReader(
return MailWithInvoice(
message.from.joinToString(), message.subject,
message.sentDate?.let { map(it) }, map(message.receivedDate), message.messageNumber,
getPlainTextBody(parts), getHtmlBody(parts),
attachmentsWithEInvoice
)
}
@ -194,6 +195,34 @@ class MailReader(
}
}
private fun getPlainTextBody(parts: Collection<MessagePart>) = getBodyWithMediaType(parts, "text/plain")
private fun getHtmlBody(parts: Collection<MessagePart>) = getBodyWithMediaType(parts, "text/html")
private fun getBodyWithMediaType(parts: Collection<MessagePart>, mediaType: String): String? = try {
val partsForMediaType = parts.filter { it.mediaType == mediaType }
if (partsForMediaType.size == 1) {
partsForMediaType.first().part.content as? String
} else if (partsForMediaType.isEmpty()) {
null
} else {
val partsForMediaTypeWithoutFilename = partsForMediaType.filter { it.part.fileName == null }
if (partsForMediaTypeWithoutFilename.size == 1) {
partsForMediaTypeWithoutFilename.first().part.content as? String
} else if (partsForMediaTypeWithoutFilename.isEmpty()) {
log.warn { "Multiple message parts with media type '$mediaType' found, but all have a filename" }
null
} else {
log.warn { "Multiple message parts with media type '$mediaType' found, but more than one does not have a filename" }
partsForMediaTypeWithoutFilename.first().part.content as? String
}
}
} catch (e: Throwable) {
log.error(e) { "Could not get message body for media type '$mediaType'" }
null
}
private fun map(date: Date): Instant =
date.toInstant()

View File

@ -9,7 +9,11 @@ class MailWithInvoice(
val sent: Instant?,
val received: Instant,
val messageNumber: Int,
val plainTextBody: String?,
val htmlBody: String?,
val attachmentsWithEInvoice: List<MailAttachmentWithEInvoice>
) {
val plainTextOrHtmlBody: String? by lazy { plainTextBody ?: htmlBody }
override fun toString() = "${(sent ?: received).atZone(ZoneId.systemDefault()).toLocalDate()} $sender: $subject, ${attachmentsWithEInvoice.size} invoice(s)"
}

View File

@ -27,6 +27,9 @@ class MailReaderTest {
val result = underTest.listAllMessagesWithEInvoice(mailAccount)
assertThat(result).isNotEmpty()
val messagesWithoutBody = result.filter { it.plainTextOrHtmlBody == null }
assertThat(messagesWithoutBody).isEmpty()
}
}