Skip to content

IMAP Examples (Swift)

Nik Wakelin edited this page Nov 23, 2021 · 2 revisions

Here are some common IMAP operations with Swift example code:

Creating a session and checking connection

You can use a session without checking, but this is useful for validating details entered by a user

let session = MCOIMAPSession()

session.hostname       = "imap.example.com"
session.port           = 993
session.connectionType = .TLS

session.username       = "[email protected]"
session.password       = "swordfish"

if let op = session.checkAccountOperation() {
  op.start { err in
    if let err = err {
      print("IMAP Connect Error: \(err)")
    } else {
      print("Successful IMAP connection!")
    }    
  }
}

List available folders

(Note: session should be an MCOIMAPSession instance as above)

if let op = session?.fetchAllFoldersOperation() {
  op.start { error, folderList in
    
    if let err = error {
      print("Error fetching folders: \(err)")
    }
    
    if let folders = folderList {
      print("Listed all IMAP Folders: \(folders.debugDescription)")
    }
    
  }

}

Search for mail since a certain date

This example function also shows you how to combine search operators.

func searchMessages(session: MCOIMAPSession, in: MCOIMAPFolder, since: Date, unreadOnly: Bool) {
  var search = MCOIMAPSearchExpression.search(sinceReceivedDate: since)
    
  if unreadOnly {
    search = MCOIMAPSearchExpression.searchAnd(search, other: MCOIMAPSearchExpression.searchUnread())
  }

  if let op = session.searchExpressionOperation(withFolder: `in`.path, expression: search) {
    op.start { error, messageIds in
      if let err = error {
        print("Error searching IMAP: \(err)")
        return
      }
      
      if let messageIds = messageIds {
        // now have a set of UIDs, we can fetch more using a fetch operation
        if let messageOp = self.session?.fetchMessagesOperation(withFolder: `in`.path, requestKind: [ .flags, .fullHeaders, .internalDate, .size, .structure], uids: messageIds) {
          
          // if you would like to fetch some non-standard headers
          messageOp.extraHeaders = [ "Delivered-To" ]

          messageOp.start { error, messages, _ in 
            if let error = error {
              print("Error fetching messages: \(error)")
              return 
            }

            if let messages = messages {
              print("Retrieved \(messages.count) message(s) from IMAP server")

              // now do whatever you need to with your messages :)
              print("Messages: \(messages.debugDescription)")

            }
          }

        }
      }
    }
  }
}