Tuesday 13 July 2021

Saving and displaying attachments with JavaMail

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.



from Saving and displaying attachments with JavaMail

No comments:

Post a Comment