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

Reply to an email and preserve its thread

See more Email Object Examples

Create a reply to with-attachments.eml. Address it to Reply-To when supplied, or to the original author otherwise. Link the reply to the original Message-ID, replace its body with a short answer, and print the destination before saving the draft.

Chilkat Objective-C Downloads

Objective-C
#import <CkoEmail.h>
#import <NSString.h>
#import <CkoStringBuilder.h>

BOOL success = NO;

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

CkoEmail *original = [[CkoEmail alloc] init];
success = [original LoadEml: @"with-attachments.eml"];
if (success != YES) {
    NSLog(@"%@",original.LastErrorText);
    return;
}

CkoEmail *reply = [[CkoEmail alloc] init];
success = [original ToReply: reply];
if (success != YES) {
    NSLog(@"%@",original.LastErrorText);
    return;
}

reply.From = @"Alex Rivera <alex@example.net>";
//  This is a reply to the author, not a reply-all. Set the destination explicitly.
[reply ClearTo];
[reply ClearCC];
[reply ClearBcc];
NSString *destination = [original GetHeaderField: @"Reply-To"];
if (destination == @"") {
    destination = original.From;
}

success = [reply AddMultipleTo: destination];
if (success != YES) {
    NSLog(@"%@",reply.LastErrorText);
    return;
}

//  Link this answer to its parent and preserve the earlier conversation references.
NSString *parentId = [original GetHeaderField: @"Message-ID"];
if (parentId != @"") {
    [reply AddHeaderField: @"In-Reply-To" fieldValue: parentId];
    CkoStringBuilder *refs = [[CkoStringBuilder alloc] init];
    [refs Append: [original GetHeaderField: @"References"]];
    if ([refs.Length intValue] > 0) {
        [refs Append: @" "];
    }

    [refs Append: parentId];
    [reply AddHeaderField: @"References" fieldValue: [refs GetAsString]];
}

//  A short text reply has no use for the original inline artwork or nested correspondence.
[reply RemoveAttachedMessages];
[reply RemoveHtmlAlternative];
[reply DropRelatedItems];
[reply SetTextBody: @"Thank you for your message." contentType: @"text/plain"];
if ([reply.NumTo intValue] < 1) {
    NSLog(@"%@",@"Reply has no destination. Review the original sender headers.");
    return;
}

NSLog(@"%@%@",@"Reply goes to: ",[reply GetToAddr: [NSNumber numberWithInt: 0]]);
NSLog(@"%@%@",@"In-Reply-To: ",[reply GetHeaderField: @"In-Reply-To"]);

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

NSLog(@"%@",@"Saved reply.eml.");