4

Iam working on a simple Apple mailkit extension but cant get something readable out of my mails.

    func allowMessageSendForSession(_ session: MEComposeSession, completion: @escaping (Error?) -> Void) {
        let mailMessage = session.mailMessage;
        let subject = mailMessage.subject
        let sender = mailMessage.fromAddress.addressString ?? "undefined";
        let data = String(data: mailMessage.rawData!, encoding: .utf8)

In data is the header and the mail body. But its filled with so many 'quoted-printable' strings.

Something like this Viele Gr=C3=BC=C3=\n=9Fe =F0=9F=A4=9D. It should be Viele Grüße .

I already tried the code in this answer https://stackoverflow.com/a/32827598/1407823 but it seems to only work with single words. I cannot get it to work with a whole text.

Is there no built in way to parse text like this?

jstedfast
  • 35,744
  • 5
  • 97
  • 110
Michael Malura
  • 1,131
  • 2
  • 13
  • 30
  • 2
    In what way are you having trouble with a whole text? – Rob Napier Nov 30 '22 at 14:50
  • The moment the code (https://stackoverflow.com/a/32827598/1407823) hits a string it cannot decode and convert to a byte it returns nil. Inside the mail are some characters like `="A`. Thats why i'am searching for robust solution. – Michael Malura Dec 01 '22 at 15:14

1 Answers1

2

There is no built-in way to decode the message, you need a RFC822 parser for example MimeParser on GitHub, available as Swift Package.

This is an example how to decode the body as plain text, messageData represents the raw data of the message

import MimeParser

do {
    let messageString = String(data: messageData, encoding: .utf8)!
    let parser = MimeParser()
    let mime = try parser.parse(messageString)
    
    switch mime.content {
        case .body(let body): print(body.raw)
        case .alternative(let mimes), .mixed(let mimes):
        if let plainTextMime = mimes.first(where: {$0.header.contentType?.subtype == "plain"}),
            let decodedBody = try plainTextMime.decodedContentString() {
            print(decodedBody)
        }
    }
} catch {
    print(error)
}

With subtype == "html" you get the HTML text, if available

vadian
  • 274,689
  • 30
  • 353
  • 361