MailKit: access rawData for email

Hi, I am trying to build a Mail 'action' extension, and want to access the email body and parse it for specific content. Not sure how to go about converting the 'rawData' that comes in the MEMessage into something that I can read.

Here's how I access the rawData property:

func decideAction(for message: MEMessage, completionHandler: @escaping (MEMessageActionDecision?) -> Void) {

     var action: MEMessageActionDecision? = nil
     if let messageData =  message.rawData {
         print("messageData = \(messageData)")
         // what to do here??
     } else {
         action = MEMessageActionDecision.invokeAgainWithBody
     }
     return action
}

The documentation just says this is 'unprocessed data':

The content is available after MailKit downloads the message. MailKit provides the content as unprocessed data. For details about the format of the data, see RFC 2822.

But I'm not sure what I'm supposed to do to go about converting the unprocessed 'data' into something that is accessible and useful to my app.

Let me know if you have any thoughts or recommendations

The docu also mentions that rawData is of data type Data (or NSData in Obj-C).

This means that you can easily convert it to a string with init(data:encoding:) see docu. RFC 2822 uses UTF-8, so you can use NSUTF8StringEncoding for encoding.

I am very new to Swift programming. But for testing I was able to access the email content with session.composeContext. I did not fully understand the reason. rawData is sometimes empty.

import MailKit

class ComposeSessionHandler: NSObject, MEComposeSessionHandler {

  func mailComposeSessionDidBegin(_ session: MEComposeSession) {

    // Perform any setup necessary for handling the compose session.

    if let data = session.composeContext.originalMessage?.rawData as? Data {
      let dataStr = String(data: data, encoding: .utf8)
      print(dataStr)       
    }

  }

  // ...

}
MailKit: access rawData for email
 
 
Q