Sample code for 30+ languages & platforms
Objective-C Requires Chilkat v11.0.0+

Find an email by subject and fetch it by IMAP UID

See more Email Object Examples

Search the selected INBOX by subject and fetch the first matching UID into an Email. The example requests complete attachment bodies and uses peek mode to preserve the read flag. Configure your own IMAP TLS endpoint and credentials.

Chilkat Objective-C Downloads

Objective-C
#import <CkoImap.h>
#import <CkoMessageSet.h>
#import <CkoEmail.h>

BOOL success = NO;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

CkoImap *imap = [[CkoImap alloc] init];
imap.Ssl = YES;
imap.Port = [NSNumber numberWithInt:993];
imap.RequireSslCertVerify = YES;
imap.PeekMode = YES;
imap.AutoDownloadAttachments = YES;
success = [imap Connect: @"imap.example.com"];
if (success != YES) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

success = [imap Login: @"MAIL_USER" password: @"MAIL_PASSWORD"];
if (success != YES) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

success = [imap SelectMailbox: @"INBOX"];
if (success != YES) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

CkoMessageSet *matches = [[CkoMessageSet alloc] init];
success = [imap QueryMbx: @"SUBJECT \"Sample message\"" bUid: YES msgSet: matches];
if (success != YES) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

if ([matches.Count intValue] == 0) {
    NSLog(@"%@",@"No matching message in INBOX.");
    success = [imap Disconnect];
    if (success != YES) {
        NSLog(@"%@",imap.LastErrorText);
        return;
    }

    return;
}

//  The search returned UIDs. Use the same identifier type for the fetch.
unsigned long uid = [matches GetId: [NSNumber numberWithInt: 0]];
CkoEmail *email = [[CkoEmail alloc] init];
success = [imap FetchEmail: NO msgId: uid bUid: YES email: email];
if (success != YES) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

NSLog(@"%@%d%@%d",@"Mailbox INBOX, UIDVALIDITY ",imap.UidValidity,@", UID ",uid);
success = [imap Disconnect];
if (success != YES) {
    NSLog(@"%@",imap.LastErrorText);
    return;
}

//  The downloaded Email remains usable after disconnecting.
NSLog(@"%@%@%@%d",@"Subject: ",email.Subject,@"  Files: ",[email.NumAttachments intValue]);

success = [email SaveEml: @"imap-received.eml"];
if (success != YES) {
    NSLog(@"%@",email.LastErrorText);
    return;
}

NSLog(@"%@",@"Saved imap-received.eml.");