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

Create a delivery failure report

See more Email Object Examples

A delivery agent can report a failure for an actual envelope recipient. Supply its observed SMTP outcome and enhanced status code, and return only the original headers when that is sufficient. This example saves a report for inspection. DSN format.

Chilkat Objective-C Downloads

Objective-C
#import <CkoEmail.h>
#import <CkoXml.h>
#import <CkoBinData.h>
#import <CkoMime.h>
#import <CkoStringBuilder.h>

BOOL success = NO;

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

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

CkoXml *fields = [[CkoXml alloc] init];
fields.Tag = @"DeliveryStatusFields";
[fields NewChild2: @"Final-Recipient" content: @"rfc822; alex@example.net"];
[fields NewChild2: @"Action" content: @"failed"];
[fields NewChild2: @"Status" content: @"5.1.1"];
[fields NewChild2: @"Diagnostic-Code" content: @"smtp; 550 5.1.1 Mailbox does not exist"];
CkoEmail *report = [[CkoEmail alloc] init];
success = [email ToDsn: @"The destination mailbox does not exist." statusFields: [fields GetXml] headerOnly: YES dsnEmail: report];
if (success != YES) {
    NSLog(@"%@",email.LastErrorText);
    return;
}

report.From = @"Mail delivery agent <postmaster@example.net>";
//  RFC 3464 puts the reporting MTA in its own block, ahead of the recipient fields.
CkoBinData *mimeBytes = [[CkoBinData alloc] init];
success = [report GetMimeBd: mimeBytes];
if (success != YES) {
    NSLog(@"%@",report.LastErrorText);
    return;
}

CkoMime *mime = [[CkoMime alloc] init];
success = [mime LoadMimeBd: mimeBytes];
if (success != YES) {
    NSLog(@"%@",mime.LastErrorText);
    return;
}

CkoMime *statusPart = [[CkoMime alloc] init];
success = [mime PartAt: [NSNumber numberWithInt: 1] subPart: statusPart];
if (success != YES) {
    NSLog(@"%@",mime.LastErrorText);
    return;
}

CkoStringBuilder *status = [[CkoStringBuilder alloc] init];
[status Append: @"Reporting-MTA: dns; mx.example.net\r\n\r\n"];
[status Append: [statusPart GetBodyDecoded]];
[statusPart SetBody: [status GetAsString]];
success = [mime SaveMime: @"delivery-status.eml"];
if (success != YES) {
    NSLog(@"%@",mime.LastErrorText);
    return;
}

NSLog(@"%@",@"Saved delivery-status.eml.");