3

I am trying to figure out what is the best approach and how to save and display attachments from mail body with JakartaMail library. I am successfully reading text part of the mail but I am struggling to save and display attachments. I think that the best way to save attachments is to save them in internal storage. I think that I should save them in internal storage and save their path in local DB so I can read it whenever is needed. I am not sure if I should save them using bitmap or what is the best approach. Here is my code that fetches mail text:

private fun parseMailContent(multipart: Multipart): Pair<String, MessageContent> {
    val messageContent = MessageContent()

    for (i in 0 until multipart.count) {
        val bodyPart: BodyPart = multipart.getBodyPart(i)

        val disposition: String? = bodyPart.disposition
        if (disposition != null && disposition.equals("ATTACHMENT", ignoreCase = true)) {
            // TODO save attachments
        }

        val content = bodyPart.contentType
        when {
            content.contains("TEXT/PLAIN", ignoreCase = true) -> {
                messageContent.text += bodyPart.content.toString()
            }
            content.contains("TEXT/HTML", ignoreCase = true) -> {
                messageContent.html += bodyPart.content.toString()
            }
            else -> {
                messageContent.apply {
                    text = ""
                    html = ""
                }
            }
        }
    }

    return Pair("", messageContent)
}

The first parameter in Pair should be path to current attachment. What should method that saves attachment in internal storage look like. I don't know how to convert bodyPart to actual attachment whether it is PDF or image or something else.

Antonio
  • 240
  • 3
  • 15
  • 1
    This might be useful https://stackoverflow.com/questions/1748183/download-attachments-using-java-mail As for where to save it, that depends on how big the files are and how many files you will be saving per email. – StephanC Jul 19 '21 at 15:12

0 Answers0