-
Notifications
You must be signed in to change notification settings - Fork 628
IMAP Examples
Using MailCore 2 is just a little more complex conceptually than the original MailCore. All fetch requests in MailCore 2 are made asynchronously through a queue. What does this mean? Well, let's take a look at a simple example:
MCOIMAPSession *session = [[MCOIMAPSession alloc] init];
[session setHostname:@"imap.gmail.com"];
[session setPort:993];
[session setUsername:@"[email protected]"];
[session setPassword:@"123456"];
[session setConnectionType:MCOConnectionTypeTLS];
MCOIMAPMessagesRequestKind requestKind = MCOIMAPMessagesRequestKindHeaders;
NSString *folder = @"INBOX";
MCOIndexSet *uids = [MCOIndexSet indexSetWithRange:MCORangeMake(1, UINT64_MAX)];
MCOIMAPFetchMessagesOperation *fetchOperation = [session fetchMessagesByUIDOperationWithFolder:folder requestKind:requestKind uids:uids];
[fetchOperation start:^(NSError * error, NSArray * fetchedMessages, MCOIndexSet * vanishedMessages) {
//We've finished downloading the messages!
//Let's check if there was an error:
if(error) {
NSLog(@"Error downloading message headers:%@", error);
}
//And, let's print out the messages...
NSLog(@"The post man delivereth:%@", fetchedMessages);
}];
// if you're running in a command line tool.
// [[NSRunLoop currentRunLoop] run];
In this sample, we retrieved and printed a list of email headers from an IMAP server. In order to execute the fetch, we request an asynchronous operation object from the MCOIMAPSession
instance with our parameters (more on this later). This operation object is able to initiate a connection to Gmail when we call the start
method. Now here's where things get a little tricky. We call the start
function with an Objective-C block, which is executed on the main thread when the fetch operation completes. The actual fetching from IMAP is done on a background thread, leaving your UI and other processing free to use the main thread.
You can update the flags for a message in MailCore 2 like so:
BOOL deleted = NEW_FLAGS & MCOMessageFlagDeleted;
MCOIMAPOperation *op = [session storeFlagsOperationWithFolder:@"INBOX"
uids:[MCOIndexSet indexSetWithIndex:MESSAGE_UID]
kind:MCOIMAPStoreFlagsRequestKindSet
flags:NEW_FLAGS];
[op start:^(NSError * error) {
if(!error) {
NSLog(@"Updated flags!");
} else {
NSLog(@"Error updating flags:%@", error);
}
if(deleted) {
MCOIMAPOperation *deleteOp = [session expungeOperation:@"INBOX"];
[deleteOp start:^(NSError *error) {
if(error) {
NSLog(@"Error expunging folder:%@", error);
} else {
NSLog(@"Successfully expunged folder");
}
}];
}
}];
As we can see, we set
the flags for the message in question, then if the new flags included a 'delete' bit, we then expunge the folder.