snipsco / Postal

A Swift framework for working with emails
MIT License
652 stars 81 forks source link

Question: How do you get the message text? #18

Closed matadan closed 8 years ago

matadan commented 8 years ago

I'm struggling to find the right API to use to retrieve the message body. If I take the raw data from a message part, I can convert it to a String but it has extraneous characters. Is there an API to use to get the contents of a message?

jeremiegirault commented 8 years ago

Hey @matadan, Postal allows you to retrieve the mail contents as Parts, but there are many uses to it. We did not provide a specific way to use them. Maybe you could create some helpers that are specific to your domain. If you want to access the textual part of the mail (if the mail has a text part), you can try to enumerate the body parts (with fetchResult.body?.allParts) and find one that has the 'text/plain' mime-type. You will then have access to the text content.

matadan commented 8 years ago

Thank you. I wrote this function:

func bodyText(body: MailPart) -> String? {
    for part in body.allParts {
        if part.mimeType.type == "text" && part.mimeType.subtype ==  "plain" {
            if let decodedData = part.data?.decodedData {
                let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) as String!

                return decodedString
            }
        }
    }

    return nil
}
jeremiegirault commented 8 years ago

I added some improvements that could simplify your loop in #21 MimeType is now Hashable and Comparable Some common types are provided for example: MimeType.textPlain You can now type if part.mimeType == MimeType.textPlain {