With trying to get to grips with the Google APIs Client Library for Objective-C for REST I came across the need to search message parts to find the plain text and HTML content of each email. Although I haven’t settled on the final way to accomplish this, one way I am testing is using .filter on an array of GTLRGmail_MessagePart’s.
What you see above is the message that has a payload which is a GTLRGmai_MessagePart, but with that part also containing an array of parts (sometimes/perhaps quite often).
As seen in the screenshot above, the filter is called “isIncluded” and throws a Bool. What happens is that if false is returned, no part is returned, but if true is returned, the GTLRGmail_MessagePart is returned and stored in “part” which is a constant we set earlier.
let part = message.payload?.parts?.filter({ (part) -> Bool in
if part.mimeType == "text/html"{
return true
}
return false
})
At the moment, the simple way I am using is to check if the mimeType contains text/html, and if so, I return that part which has the body.
If a part is returned, it will contain text/html content in the body.data property of which we can decode the base64 stored there and convert it to HTML as seen in this tutorial.
Before you implement this code, be aware that there is technically no limit to how many parts are embedded in parts. The chain can go on for a while, which for those edge cases you would need to use a recursive search to find the HTML content you are looking for. An example is when you come across the multipart/related mimeType. If this mime type is contained within the payload, then the payload will have parts within of which some are items such as images, and another part, the first, could contain mimeType.alternative, at which point you would likely find your plain text or html mime type you are looking for.
This is still a work in progress to find the optimal solution for parsing the message. An alternative option I am investigating is using a for loop to check each part, and likely nest a for loop within that loop to dig deeper, or use recursion to find what I am looking for.
Leave a Reply
You must be logged in to post a comment.